如何使用Windows批处理文件遍历文本文件中的每一行?

时间:2021-05-20 19:44:10

I would like to know how to loop through each line in a text file using a Windows batch file and process each line of text in succession.

我想知道如何使用Windows批处理文件遍历文本文件中的每一行,并连续处理每行文本。

11 个解决方案

#1


263  

The posts below helped greatly, but did not do what I stated in my question where I needed to process the entire line as a whole. Here is what I found to work.

下面的帖子有很大帮助,但没有按照我在问题中所说的那样做,我需要处理整个整行。这是我发现的工作方式。

for /F "tokens=*" %%A in (myfile.txt) do [process] %%A

The tokens keyword with an asterisk (*) will pull all text for the entire line. If you don't put in the asterisk it will only pull the first word on the line. I assume it has to do with spaces.

带有星号(*)的tokens关键字将拉出整行的所有文本。如果你没有放入星号,它只会拉动该行的第一个单词。我认为它与空间有关。

For Command on TechNet

对于TechNet上的命令

I appreciate all of the posts!

我感谢所有的帖子!


If there are spaces in your file path, you need to use usebackq. For example.

如果文件路径中有空格,则需要使用usebackq。例如。

for /F "usebackq tokens=*" %%A in ("my file.txt") do [process] %%A

#2


52  

From the Windows command line reference:

从Windows命令行参考:

To parse a file, ignoring commented lines, type:

要解析文件,忽略注释行,请键入:

for /F "eol=; tokens=2,3* delims=," %i in (myfile.txt) do @echo %i %j %k

This command parses each line in Myfile.txt, ignoring lines that begin with a semicolon and passing the second and third token from each line to the FOR body (tokens are delimited by commas or spaces). The body of the FOR statement references %i to get the second token, %j to get the third token, and %k to get all of the remaining tokens.

此命令解析Myfile.txt中的每一行,忽略以分号开头的行,并将第二个和第三个标记从每个行传递给FOR主体(标记由逗号或空格分隔)。 FOR语句的主体引用%i来获取第二个标记,%j来获取第三个标记,使用%k来获取所有剩余的标记。

If the file names that you supply contain spaces, use quotation marks around the text (for example, "File Name"). To use quotation marks, you must use usebackq. Otherwise, the quotation marks are interpreted as defining a literal string to parse.

如果您提供的文件名包含空格,请在文本周围使用引号(例如,“文件名”)。要使用引号,必须使用usebackq。否则,引号将被解释为定义要解析的文字字符串。

By the way, you can find the command-line help file on most Windows systems at:

顺便说一句,您可以在大多数Windows系统上找到命令行帮助文件:

 "C:\WINDOWS\Help\ntcmds.chm"

#3


30  

In a Batch File you MUST use %% instead of % : (Type help for)

在批处理文件中,您必须使用%%而不是%:(输入帮助)

for /F "tokens=1,2,3" %%i in (myfile.txt) do call :process %%i %%j %%k
goto thenextstep
:process
set VAR1=%1
set VAR2=%2
set VAR3=%3
COMMANDS TO PROCESS INFORMATION
goto :EOF

What this does: The "do call :process %%i %%j %%k" at the end of the for command passes the information acquired in the for command from myfile.txt to the "process" 'subroutine'.

这样做:for命令末尾的“do call:process %% i %% j %% k”将forfile命令中获取的信息从myfile.txt传递给“process”'子例程'。

When you're using the for command in a batch program, you need to use double % signs for the variables.

在批处理程序中使用for命令时,需要对变量使用双%符号。

The following lines pass those variables from the for command to the process 'sub routine' and allow you to process this information.

以下行将那些变量从for命令传递给进程'sub routine',并允许您处理此信息。

set VAR1=%1
 set VAR2=%2
 set VAR3=%3

I have some pretty advanced uses of this exact setup that I would be willing to share if further examples are needed. Add in your EOL or Delims as needed of course.

如果需要进一步的示例,我会对这个确切的设置有一些非常高级的用法,我愿意分享。当然,根据需要添加您的EOL或Delims。

#4


22  

Improving the first "FOR /F.." answer: What I had to do was to call execute every script listed in MyList.txt, so it worked for me:

改进第一个“FOR / F ..”答案:我必须做的是调用执行MyList.txt中列出的每个脚本,所以它对我有用:

for /F "tokens=*" %A in  (MyList.txt) do CALL %A ARG1

--OR, if you wish to do it over the multiple line:

- 或者,如果您希望通过多行执行此操作:

for /F "tokens=*" %A in  (MuList.txt) do (
ECHO Processing %A....
CALL %A ARG1
)

Edit: The example given above is for executing FOR loop from command-prompt; from a batch-script, an extra % needs to be added, as shown below:

编辑:上面给出的例子是从命令提示符执行FOR循环;从批处理脚本中,需要添加额外的%,如下所示:

---START of MyScript.bat---
@echo off
for /F "tokens=*" %%A in  ( MyList.TXT) do  (
   ECHO Processing %%A.... 
   CALL %%A ARG1 
)
@echo on
;---END of MyScript.bat---

#5


20  

@MrKraus's answer is instructive. Further, let me add that if you want to load a file located in the same directory as the batch file, prefix the file name with %~dp0. Here is an example:

@ MrKraus的回答很有启发性。此外,让我补充一点,如果要加载与批处理文件位于同一目录中的文件,请在文件名前加上%~dp0。这是一个例子:

cd /d %~dp0
for /F "tokens=*" %%A in (myfile.txt) do [process] %%A

NB:: If your file name or directory (e.g. myfile.txt in the above example) has a space (e.g. 'my file.txt' or 'c:\Program Files'), use:

NB ::如果您的文件名或目录(例如上例中的myfile.txt)有空格(例如'my file.txt'或'c:\ Program Files'),请使用:

for /F "tokens=*" %%A in ('type "my file.txt"') do [process] %%A

, with the type keyword calling the type program, which displays the contents of a text file. If you don't want to suffer the overhead of calling the type command you should change the directory to the text file's directory. Note that type is still required for file names with spaces.

,使用type关键字调用类型程序,它显示文本文件的内容。如果您不想承受调用type命令的开销,则应将目录更改为文本文件的目录。请注意,带空格的文件名仍需要类型。

I hope this helps someone!

我希望这可以帮助别人!

#6


14  

The accepted answer is good, but has two limitations.
It drops empty lines and lines beginning with ;

接受的答案很好,但有两个局限。它会以空白行和行开头;

To read lines of any content, you need the delayed expansion toggling technic.

要读取任何内容的行,您需要延迟扩展切换技术。

@echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ text.txt"`) do (
    set "var=%%a"
    SETLOCAL EnableDelayedExpansion
    set "var=!var:*:=!"
    echo(!var!
    ENDLOCAL
)

Findstr is used to prefix each line with the line number and a colon, so empty lines aren't empty anymore.

Findstr用于为每行添加行号和冒号,因此空行不再为空。

DelayedExpansion needs to be disabled, when accessing the %%a parameter, else exclamation marks ! and carets ^ will be lost, as they have special meanings in that mode.

当访问%% a参数时,需要禁用DelayedExpansion,否则感叹号!和插入符号^将丢失,因为它们在该模式中具有特殊含义。

But to remove the line number from the line, the delayed expansion needs to be enabled.
set "var=!var:*:=!" removes all up to the first colon (using delims=: would remove also all colons at the beginning of a line, not only the one from findstr).
The endlocal disables the delayed expansion again for the next line.

但要从行中删除行号,需要启用延迟扩展。设置“var =!var:*:=!”删除所有直到第一个冒号(使用delims =:也将删除行开头的所有冒号,而不仅是来自findstr的冒号)。 endlocal再次禁用下一行的延迟扩展。

The only limitation is now the line length limit of ~8191, but there seems no way to overcome this.

唯一的限制是现在线路长度限制为~8191,但似乎没有办法克服这一点。

#7


13  

Or, you may exclude the options in quotes:

或者,您可以在引号中排除选项:

FOR /F %%i IN (myfile.txt) DO ECHO %%i

#8


9  

Here's a bat file I wrote to execute all SQL scripts in a folder:

这是我写的一个bat文件,用于执行文件夹中的所有SQL脚本:

REM ******************************************************************
REM Runs all *.sql scripts sorted by filename in the current folder.
REM To use integrated auth change -U <user> -P <password> to -E
REM ******************************************************************

dir /B /O:n *.sql > RunSqlScripts.tmp
for /F %%A in (RunSqlScripts.tmp) do osql -S (local) -d DEFAULT_DATABASE_NAME -U USERNAME_GOES_HERE -P PASSWORD_GOES_HERE -i %%A
del RunSqlScripts.tmp

#9


5  

If you have an NT-family Windows (one with cmd.exe as the shell), try the FOR /F command.

如果您有一个NT系列Windows(一个以cmd.exe作为shell),请尝试使用FOR / F命令。

#10


1  

Modded examples here to list our Rails apps on Heroku - thanks!

这里的Modded示例列出了我们在Heroku上的Rails应用程序 - 谢谢!

cmd /C "heroku list > heroku_apps.txt"
find /v "=" heroku_apps.txt | find /v ".TXT" | findstr /r /v /c:"^$" > heroku_apps_list.txt
for /F "tokens=1" %%i in (heroku_apps_list.txt) do heroku run bundle show rails --app %%i

Full code here.

完整代码在这里。

#11


0  

The accepted anwser using cmd.exe and

接受的anwser使用cmd.exe和

for /F "tokens=*" %F in (file.txt) do whatever "%F" ...

works only for "normal" files. It fails miserably with huge files.

仅适用于“普通”文件。它与巨大的文件惨遭失败。

For big files, you may need to use Powershell and something like this:

对于大文件,您可能需要使用Powershell,如下所示:

[IO.File]::ReadLines("file.txt") | ForEach-Object { whatever "$_" }

or if you have enough memory:

或者如果你有足够的记忆:

foreach($line in [System.IO.File]::ReadLines("file.txt")) { whatever "$line" } 

This worked for me with a 250 MB file containing over 2 million lines, where the for /F ... command got stuck after a few thousand lines.

这对我来说是一个包含超过200万行的250 MB文件,其中for / F ...命令在几千行后被卡住了。

For the differences between foreach and ForEach-Object, see Getting to Know ForEach and ForEach-Object.

有关foreach和ForEach-Object之间的差异,请参阅了解ForEach和ForEach-Object。

(credits: Read file line by line in PowerShell )

(学分:在PowerShell中逐行读取文件)

#1


263  

The posts below helped greatly, but did not do what I stated in my question where I needed to process the entire line as a whole. Here is what I found to work.

下面的帖子有很大帮助,但没有按照我在问题中所说的那样做,我需要处理整个整行。这是我发现的工作方式。

for /F "tokens=*" %%A in (myfile.txt) do [process] %%A

The tokens keyword with an asterisk (*) will pull all text for the entire line. If you don't put in the asterisk it will only pull the first word on the line. I assume it has to do with spaces.

带有星号(*)的tokens关键字将拉出整行的所有文本。如果你没有放入星号,它只会拉动该行的第一个单词。我认为它与空间有关。

For Command on TechNet

对于TechNet上的命令

I appreciate all of the posts!

我感谢所有的帖子!


If there are spaces in your file path, you need to use usebackq. For example.

如果文件路径中有空格,则需要使用usebackq。例如。

for /F "usebackq tokens=*" %%A in ("my file.txt") do [process] %%A

#2


52  

From the Windows command line reference:

从Windows命令行参考:

To parse a file, ignoring commented lines, type:

要解析文件,忽略注释行,请键入:

for /F "eol=; tokens=2,3* delims=," %i in (myfile.txt) do @echo %i %j %k

This command parses each line in Myfile.txt, ignoring lines that begin with a semicolon and passing the second and third token from each line to the FOR body (tokens are delimited by commas or spaces). The body of the FOR statement references %i to get the second token, %j to get the third token, and %k to get all of the remaining tokens.

此命令解析Myfile.txt中的每一行,忽略以分号开头的行,并将第二个和第三个标记从每个行传递给FOR主体(标记由逗号或空格分隔)。 FOR语句的主体引用%i来获取第二个标记,%j来获取第三个标记,使用%k来获取所有剩余的标记。

If the file names that you supply contain spaces, use quotation marks around the text (for example, "File Name"). To use quotation marks, you must use usebackq. Otherwise, the quotation marks are interpreted as defining a literal string to parse.

如果您提供的文件名包含空格,请在文本周围使用引号(例如,“文件名”)。要使用引号,必须使用usebackq。否则,引号将被解释为定义要解析的文字字符串。

By the way, you can find the command-line help file on most Windows systems at:

顺便说一句,您可以在大多数Windows系统上找到命令行帮助文件:

 "C:\WINDOWS\Help\ntcmds.chm"

#3


30  

In a Batch File you MUST use %% instead of % : (Type help for)

在批处理文件中,您必须使用%%而不是%:(输入帮助)

for /F "tokens=1,2,3" %%i in (myfile.txt) do call :process %%i %%j %%k
goto thenextstep
:process
set VAR1=%1
set VAR2=%2
set VAR3=%3
COMMANDS TO PROCESS INFORMATION
goto :EOF

What this does: The "do call :process %%i %%j %%k" at the end of the for command passes the information acquired in the for command from myfile.txt to the "process" 'subroutine'.

这样做:for命令末尾的“do call:process %% i %% j %% k”将forfile命令中获取的信息从myfile.txt传递给“process”'子例程'。

When you're using the for command in a batch program, you need to use double % signs for the variables.

在批处理程序中使用for命令时,需要对变量使用双%符号。

The following lines pass those variables from the for command to the process 'sub routine' and allow you to process this information.

以下行将那些变量从for命令传递给进程'sub routine',并允许您处理此信息。

set VAR1=%1
 set VAR2=%2
 set VAR3=%3

I have some pretty advanced uses of this exact setup that I would be willing to share if further examples are needed. Add in your EOL or Delims as needed of course.

如果需要进一步的示例,我会对这个确切的设置有一些非常高级的用法,我愿意分享。当然,根据需要添加您的EOL或Delims。

#4


22  

Improving the first "FOR /F.." answer: What I had to do was to call execute every script listed in MyList.txt, so it worked for me:

改进第一个“FOR / F ..”答案:我必须做的是调用执行MyList.txt中列出的每个脚本,所以它对我有用:

for /F "tokens=*" %A in  (MyList.txt) do CALL %A ARG1

--OR, if you wish to do it over the multiple line:

- 或者,如果您希望通过多行执行此操作:

for /F "tokens=*" %A in  (MuList.txt) do (
ECHO Processing %A....
CALL %A ARG1
)

Edit: The example given above is for executing FOR loop from command-prompt; from a batch-script, an extra % needs to be added, as shown below:

编辑:上面给出的例子是从命令提示符执行FOR循环;从批处理脚本中,需要添加额外的%,如下所示:

---START of MyScript.bat---
@echo off
for /F "tokens=*" %%A in  ( MyList.TXT) do  (
   ECHO Processing %%A.... 
   CALL %%A ARG1 
)
@echo on
;---END of MyScript.bat---

#5


20  

@MrKraus's answer is instructive. Further, let me add that if you want to load a file located in the same directory as the batch file, prefix the file name with %~dp0. Here is an example:

@ MrKraus的回答很有启发性。此外,让我补充一点,如果要加载与批处理文件位于同一目录中的文件,请在文件名前加上%~dp0。这是一个例子:

cd /d %~dp0
for /F "tokens=*" %%A in (myfile.txt) do [process] %%A

NB:: If your file name or directory (e.g. myfile.txt in the above example) has a space (e.g. 'my file.txt' or 'c:\Program Files'), use:

NB ::如果您的文件名或目录(例如上例中的myfile.txt)有空格(例如'my file.txt'或'c:\ Program Files'),请使用:

for /F "tokens=*" %%A in ('type "my file.txt"') do [process] %%A

, with the type keyword calling the type program, which displays the contents of a text file. If you don't want to suffer the overhead of calling the type command you should change the directory to the text file's directory. Note that type is still required for file names with spaces.

,使用type关键字调用类型程序,它显示文本文件的内容。如果您不想承受调用type命令的开销,则应将目录更改为文本文件的目录。请注意,带空格的文件名仍需要类型。

I hope this helps someone!

我希望这可以帮助别人!

#6


14  

The accepted answer is good, but has two limitations.
It drops empty lines and lines beginning with ;

接受的答案很好,但有两个局限。它会以空白行和行开头;

To read lines of any content, you need the delayed expansion toggling technic.

要读取任何内容的行,您需要延迟扩展切换技术。

@echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ text.txt"`) do (
    set "var=%%a"
    SETLOCAL EnableDelayedExpansion
    set "var=!var:*:=!"
    echo(!var!
    ENDLOCAL
)

Findstr is used to prefix each line with the line number and a colon, so empty lines aren't empty anymore.

Findstr用于为每行添加行号和冒号,因此空行不再为空。

DelayedExpansion needs to be disabled, when accessing the %%a parameter, else exclamation marks ! and carets ^ will be lost, as they have special meanings in that mode.

当访问%% a参数时,需要禁用DelayedExpansion,否则感叹号!和插入符号^将丢失,因为它们在该模式中具有特殊含义。

But to remove the line number from the line, the delayed expansion needs to be enabled.
set "var=!var:*:=!" removes all up to the first colon (using delims=: would remove also all colons at the beginning of a line, not only the one from findstr).
The endlocal disables the delayed expansion again for the next line.

但要从行中删除行号,需要启用延迟扩展。设置“var =!var:*:=!”删除所有直到第一个冒号(使用delims =:也将删除行开头的所有冒号,而不仅是来自findstr的冒号)。 endlocal再次禁用下一行的延迟扩展。

The only limitation is now the line length limit of ~8191, but there seems no way to overcome this.

唯一的限制是现在线路长度限制为~8191,但似乎没有办法克服这一点。

#7


13  

Or, you may exclude the options in quotes:

或者,您可以在引号中排除选项:

FOR /F %%i IN (myfile.txt) DO ECHO %%i

#8


9  

Here's a bat file I wrote to execute all SQL scripts in a folder:

这是我写的一个bat文件,用于执行文件夹中的所有SQL脚本:

REM ******************************************************************
REM Runs all *.sql scripts sorted by filename in the current folder.
REM To use integrated auth change -U <user> -P <password> to -E
REM ******************************************************************

dir /B /O:n *.sql > RunSqlScripts.tmp
for /F %%A in (RunSqlScripts.tmp) do osql -S (local) -d DEFAULT_DATABASE_NAME -U USERNAME_GOES_HERE -P PASSWORD_GOES_HERE -i %%A
del RunSqlScripts.tmp

#9


5  

If you have an NT-family Windows (one with cmd.exe as the shell), try the FOR /F command.

如果您有一个NT系列Windows(一个以cmd.exe作为shell),请尝试使用FOR / F命令。

#10


1  

Modded examples here to list our Rails apps on Heroku - thanks!

这里的Modded示例列出了我们在Heroku上的Rails应用程序 - 谢谢!

cmd /C "heroku list > heroku_apps.txt"
find /v "=" heroku_apps.txt | find /v ".TXT" | findstr /r /v /c:"^$" > heroku_apps_list.txt
for /F "tokens=1" %%i in (heroku_apps_list.txt) do heroku run bundle show rails --app %%i

Full code here.

完整代码在这里。

#11


0  

The accepted anwser using cmd.exe and

接受的anwser使用cmd.exe和

for /F "tokens=*" %F in (file.txt) do whatever "%F" ...

works only for "normal" files. It fails miserably with huge files.

仅适用于“普通”文件。它与巨大的文件惨遭失败。

For big files, you may need to use Powershell and something like this:

对于大文件,您可能需要使用Powershell,如下所示:

[IO.File]::ReadLines("file.txt") | ForEach-Object { whatever "$_" }

or if you have enough memory:

或者如果你有足够的记忆:

foreach($line in [System.IO.File]::ReadLines("file.txt")) { whatever "$line" } 

This worked for me with a 250 MB file containing over 2 million lines, where the for /F ... command got stuck after a few thousand lines.

这对我来说是一个包含超过200万行的250 MB文件,其中for / F ...命令在几千行后被卡住了。

For the differences between foreach and ForEach-Object, see Getting to Know ForEach and ForEach-Object.

有关foreach和ForEach-Object之间的差异,请参阅了解ForEach和ForEach-Object。

(credits: Read file line by line in PowerShell )

(学分:在PowerShell中逐行读取文件)