如何用批处理读取文件并在循环中使用它来写入临时文件

时间:2015-01-25 20:24:06

标签: batch-file

我正在使用批处理脚本打开文件并创建临时文件。我从文件中读取文本并按行分割。然后它想写入一个临时文件,启动firefox并在其中打开一个链接。在循环结束之前,它将删除临时文件

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"

)

它没有完成这项工作,并且在进入循环时会出现一些错误。

myfile.txt包含

something
something else
other thing
some other thing

1 个答案:

答案 0 :(得分:1)

以下是您的批处理代码略有改进:

@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"
)

重要的是在第三个echo命令中使用^转义括号,否则)被解释为DO块的结尾。

请注意,在文件 myfile.txt 中输入命令提示符窗口cmd /?后,如果上一个帮助页面输出中列出了一些字符,则此批处理代码将无效。像

这样的人物
%<>&()[]{}^=;!'+`,~

在批处理语法中有特殊含义。

因此,使用延迟环境变量扩展可能会更好地使用下面的批处理代码。

@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
相关问题