edinvnode
edinvnode

Reputation: 3537

how to read file with batch and use it in loop to write in temporary file

I am using a batch script to open a file and create a temporary file. I reads text from a file and splits per lines. Then it's suppose to write into a temporary file, start firefox and open a link in it. Before the end of the loop it will delete the temporary file

taskkill /f /im "firefox.exe"

FOR /f "tokens=* delims=,"  %%i in (myfile.txt) do (
    @echo %%i
    @echo %%i > tmpkeywords.txt
    timeout 5


start /B "" "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
timeout 10
ECHO Now running the macro (in a 2nd Tab)...
"C:\Program Files (x86)\Mozilla Firefox\firefox.exe" "wwww.google.com"

ECHO FINISHED!

timeout 60

REM REMOVE THE TEMPORARY FILE

del "C:\tmpkeywords.txt"

)

It doesn't do the job and has some error when it goes into the loop.

myfile.txt contains

something
something else
other thing
some other thing

Upvotes: 0

Views: 255

Answers (1)

Mofi
Mofi

Reputation: 49086

Here is your batch code a little bit improved:

@echo off
%SystemRoot%\System32\taskkill.exe /f /im "firefox.exe"

for /f "tokens=* delims=," %%i in (myfile.txt) do (
    echo %%i
    echo %%i>"%TEMP%\tmpkeywords.txt"
    %SystemRoot%\System32\timeout.exe 5
    start "" /B "%ProgramFiles(x86)%\Mozilla Firefox\firefox.exe"
    %SystemRoot%\System32\timeout.exe 10
    echo Now running the macro ^(in a 2nd tab^)...
    "%ProgramFiles(x86)%\Mozilla Firefox\firefox.exe" "wwww.google.com"

    echo FINISHED!

    %SystemRoot%\System32\timeout.exe 60

    REM REMOVE THE TEMPORARY FILE

    del "%TEMP%\tmpkeywords.txt"
)

Important is to escape the parentheses in third echo command with ^ or otherwise ) is interpreted as end of DO block.

And please note that with some characters listed on last help page output after entering in a command prompt window cmd /? in file myfile.txt this batch code would not work. Characters like

%<>&()[]{}^=;!'+`,~

have special meanings in batch syntax.

Therefore a batch code like below is perhaps better using delayed environment variable expansion.

@echo off
setlocal EnableDelayedExpansion
%SystemRoot%\System32\taskkill.exe /f /im "firefox.exe"

for /f "tokens=* delims=," %%i in (myfile.txt) do (
    set "Line=%%i"
    echo !Line!>"%TEMP%\tmpkeywords.txt"
    %SystemRoot%\System32\timeout.exe 5
    start "" /B "%ProgramFiles(x86)%\Mozilla Firefox\firefox.exe"
    %SystemRoot%\System32\timeout.exe 10
    echo Now running the macro ^(in a 2nd tab^)...
    "%ProgramFiles(x86)%\Mozilla Firefox\firefox.exe" "wwww.google.com"

    echo FINISHED!

    %SystemRoot%\System32\timeout.exe 60

    REM REMOVE THE TEMPORARY FILE

    del "%TEMP%\tmpkeywords.txt"
)
endlocal

Upvotes: 1

Related Questions