windows Windows命令行上的foreach循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9047477/
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
Foreach loop on windows command line?
提问by Adam S
I have a command line which copies files from folder A to folder B:
我有一个将文件从文件夹 A 复制到文件夹 B 的命令行:
copy A\* B\
I would now like to delete all files in B that are present in A, non-recursively. I can list the files in A like this:
我现在想以非递归方式删除 B 中存在于 A 中的所有文件。我可以像这样列出 A 中的文件:
dir /b /a-d A
With the output being:
输出为:
f0.txt
f1.txt
f2.txt
Here is the pseudocode for what I would like to do:
这是我想要做的伪代码:
foreach in <dir /b /a-d A output>:
del B$1
Is there a windows command-line syntax that will execute a command, using the output of another command as an input? I am aware of the piping operator ( | ) but do not know of a way that this could be used to accomplish this task. Any help would be appreciate.
是否有使用另一个命令的输出作为输入来执行命令的 Windows 命令行语法?我知道管道运算符 ( | ),但不知道可以使用它来完成此任务的方法。任何帮助将不胜感激。
Restriction: Only commands available by default in Windows 7.
限制:只有在 Windows 7 中默认可用的命令。
回答by Joey
You can iterate over files with
您可以使用
for %x in (*) do ...
which is also a lot more robust than trying to iterate over the output of a command for this use case.
这也比尝试迭代此用例的命令输出要健壮得多。
So
所以
for %f in (A\*) do del "B\%~nxf"
or, if you need this in a batch file instead of the command line:
或者,如果您需要在批处理文件而不是命令行中使用它:
for %%f in (A\*) do del "B\%%~nxf"
%~nxf
returns only the file name and extension of each file since it will be prefixed with A\
and you want to delete it in B.
%~nxf
仅返回每个文件的文件名和扩展名,因为它将以前缀为前缀,A\
并且您想在 B 中删除它。
Add > nul 2>&1
to suppress any output (error messages may appear when you try deleting files that don't exist).
添加> nul 2>&1
以抑制任何输出(尝试删除不存在的文件时可能会出现错误消息)。
Just for completeness, you can in fact iterate over the output of a command in almost the same way:
为了完整起见,您实际上可以以几乎相同的方式迭代命令的输出:
for /f %x in ('some command') do ...
but there are several problems with doing this and in the case of iterating over dir
output it's rarely necessary, hence I don't recommend it.
但是这样做有几个问题,并且在迭代dir
输出的情况下很少需要,因此我不推荐它。
And since you are on Windows 7, you have PowerShell as well:
由于您使用的是 Windows 7,因此您还拥有 PowerShell:
Get-ChildItem A\* | ForEach-Object { Remove-Item ('B\' + $_.Name) }
or shorter:
或更短:
ls A\* | % { rm B$($_.Name) }