windows 带有 for 循环和管道的批处理脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6026773/
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
Batch script with for loop and pipe
提问by Gilbeg
I would like all the csv files in a directory which filename does not contain word "summary". Inside the command prompt I can type the following command
我想要文件名不包含“摘要”一词的目录中的所有 csv 文件。在命令提示符中,我可以键入以下命令
dir /b my_dir\*.csv | find /V "summary"
When I try to transfer the above command into a batch file I run into a problem in that the pipe command is not supported in the for loop. That is I cannot do the following
当我尝试将上述命令传输到批处理文件中时,我遇到了一个问题,即 for 循环中不支持管道命令。那就是我不能做以下事情
FOR /f %%A in ('dir /b my_dir\*.csv | find /V "summary"') do (
rem want to do something here
)
Can somebody shed some light to me on how to solve the problem above?
有人可以告诉我如何解决上述问题吗?
Thanks in advance!
提前致谢!
回答by Andriy M
You need to escape the |
character to prevent its being interpreted at the time of parsing the loop command. Use ^
to escape it:
您需要对|
字符进行转义以防止在解析循环命令时对其进行解释。使用^
逃脱它:
FOR /f "delims=" %%A in ('dir /b "my_dir\*.csv" ^| find /V "summary"') do (
rem do what you want with %%A here
)
Once escaped, the |
becomes part of the '
-delimited string. It is only interpreted as a special symbol when that string is parsed separately from the loop, as a "sub-command", according to the syntax. And that is done afterparsing the loop.
一旦转义,就|
成为'
-delimited 字符串的一部分。根据语法,当该字符串与循环分开解析时,它仅被解释为特殊符号,作为“子命令”。这是在解析循环后完成的。
回答by kxs
If you get the problem that Gilbeg got "find: /V': No such file or directory" then it's most likely you have cygwin, or similar, in your path and the batch file's not using the Windows find command. If you modify your script to use the absolute path of the Windows find then the error will go away:
如果您遇到 Gilbeg 遇到“find: /V': No such file or directory”的问题,那么很可能您的路径中有 cygwin 或类似文件,并且批处理文件未使用 Windows find 命令。如果您修改脚本以使用 Windows find 的绝对路径,则错误将消失:
FOR /f "delims=" %%A in ('dir /b "my_dir\*.csv" ^| %SYSTEMROOT%\system32\find.exe /V "summary"') do (
rem want to do something here with %%A
)
回答by David Rogers
You can also just embed a double-quoted string inside the single-quotes string, as in:
您也可以在单引号字符串中嵌入一个双引号字符串,如下所示:
FOR /f "delims=" %%A in ('"dir /b my_dir\*.csv | find /I /V "summary""') do @( ECHO Do something with "%%A" )
回答by Philip Sheard
have a look at the Windows PowerShell. Not that I have ever used it myself, mind.
看看 Windows PowerShell。并不是说我自己曾经使用过它,请注意。