如何使用 Windows 批处理文件遍历文本文件中的每一行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/155932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you loop through each line in a text file using a windows batch file?
提问by Mr. Kraus
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 批处理文件遍历文本文件中的每一行并连续处理每一行文本。
回答by Mr. Kraus
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 关键字将提取整行的所有文本。如果您不输入星号,它只会拉出该行的第一个单词。我认为它与空格有关。
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
回答by Ash
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"
回答by user332474
In a Batch File you MUSTuse %%
instead of %
: (Type help for
)
在批处理文件中,您必须使用%%
而不是%
: (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”将在 for 命令中获取的信息从 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 命令传递到进程“子例程”,并允许您处理此信息。
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。
回答by Yogesh Mahajan
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---
回答by Marvin Thobejane
@MrKraus's answeris instructive. Further, let me add that if you want to load a file located in the same directoryas 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:
注意::如果您的文件名或目录(例如上例中的 myfile.txt)有空格(例如“my file.txt”或“c:\Program Files”),请使用:
for /F "tokens=*" %%A in ('type "my file.txt"') do [process] %%A
, with the typekeyword 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
程序,该程序显示文本文件的内容。如果您不想承受调用 type 命令的开销,您应该将目录更改为文本文件的目录。请注意,带有空格的文件名仍然需要 type 。
I hope this helps someone!
我希望这可以帮助别人!
回答by jeb
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.
DelayedExpansion 需要禁用,访问%%a
参数时,否则感叹号!
和插入符号^
将丢失,因为它们在该模式下具有特殊含义。
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.
但是要从行中删除行号,需要启用延迟扩展。set "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 的行长度限制,但似乎没有办法克服这一点。
回答by Paul
Or, you may exclude the options in quotes:
或者,您可以排除引号中的选项:
FOR /F %%i IN (myfile.txt) DO ECHO %%i
回答by Paul
Here's a bat file I wrote to execute all SQL scripts in a folder:
这是我编写的用于执行文件夹中所有 SQL 脚本的 bat 文件:
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
回答by Michael Ratanapintha
If you have an NT-family Windows (one with cmd.exe
as the shell), try the FOR /F command.
如果您有 NT 系列的 Windows(带有cmd.exe
外壳的Windows ),请尝试FOR /F 命令。
回答by mivk
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-对象。
(credits: Read file line by line in PowerShell)
(学分:在 PowerShell 中逐行读取文件)