简体   繁体   中英

Batch script - replace string for another string from received from variable

I have this batch script which has the objective of retrieving a URL from an input, save it to a variable. Then this URL should have a part of it, a 3-4 letters string replaced by another string which is inside a list in a file (lista.txt). Then, the script should open the Chrome browser and one tab for each new URL generated by the string replacement. I understand there are several other ways to do that, but I intend to keep using the batch file and check where my mistake is. The script seem to be working until I get to the point where the string replacement by another string coming from a variable. This is the script:

@echo off
set BROWSER=chrome.exe
set /p URL=Type the URL:
echo.
for /f %%i in (Lista.txt) do (
    set URL=%%URL:%IBOV%=%i%%
    echo %URL%
    START %BROWSER% -new-tab "%URL%"
)
Pause

contents of lista.txt:

IBOV
GNDI3
USIM5
OIBR3
MEAL3
ETER3
COGN3
TASA4
BBDC4
ITUB4
SUZB3
VALE3
PETR4
RAIL3

Looks like classical delayed expansion problem. Though I don't have preset the IBOV variable that you are using ,neither the content of Lista.txt I would suggest that this might help you:

@echo off
setlocal enableDelayedExpansion
set BROWSER=chrome.exe
set /p URL=Type the URL:
echo.
for /f %%i in (Lista.txt) do (
    set URL=!URL:IBOV=%%i!
    echo !URL!
    START %BROWSER% -new-tab "!URL!"
)
Pause

Also you are accessing the %%i token in a wrong way.

Is there really an IBOV variable set before the script starts? You might need splitting or substring substitution.

CALL set "URL=%%URL:%IBOV%=%%i%%"
CALL    echo %%URL%%
CALL START "" %BROWSER% -new-tab "%%URL%%"

Please search SO for "delayed expansion" for an explanation. The "problem" has been described hundreds of times. The syntax shown should cure the echo . Not so sure about the start but reading up on delayed expansion should provide pointers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM