英文:
How to create batch that runs multiple commands for output files
问题
我正在创建一个批处理文件,我需要它在一个可能包含数百个文件的文件夹中运行两个不同的脚本。
第一个脚本(abc2xyz)将一个文件从.abc转换为.xyz
第二个脚本(procxyz)处理.xyz
```bash
for %%f in (*.abc) do (
abc2xyz %%f
procxyz %%~nf.xyz
)
第一个脚本输出.xyz没问题。
第二个脚本在文件夹中对所有转换后的xyz文件重复运行,而不是只对刚刚转换的文件运行。
我猜测问题可能出在*.xyz,但是我该如何更改它以在刚刚转换的文件上运行,而不是每次转换一个文件时都在所有.xyz文件上运行?
<details>
<summary>英文:</summary>
I am creating a batch file and I need it to run 2 different scripts on files in a folder with potentially hundreds of files.
The 1st script (abc2xyz) converts a file from .abc to .xyz
The 2nd script (procxyz) processes the .xyz
for %%f in (*.abc) do (
abc2xyz %%f
procxyz *.xyz
)
The 1st script outputs .xyz just fine.
The 2nd script repeats running on ALL converted xyz files in the folder following each converted file instead of running on just the one that was just converted.
I can probably guess *.xyz is a problem, but how would I change this to process on the recent converted file instead of all .xyz files each time a file is converted?
</details>
# 答案1
**得分**: 0
你想在第二个命令中使用 %%f 参数的文件名。这可以通过对 %%f 参数应用 ~n 修改来实现。
有关此语法的详细信息和更多信息,请参阅 for /?。
for %%f in (*.abc) do (
abc2xyz %%f
procxyz %%~nf.xyz
)
<details>
<summary>英文:</summary>
You want to use the filename of the %%f parameter in the second command. This can be done by the ~n change to the %%f parameter.
See for /? for the details and more info regarding this syntax.
for %%f in (*.abc) do (
abc2xyz %%f
procxyz %%~nf.xyz
)
</details>
# 答案2
**得分**: 0
每次进入循环时,每个命令都会被执行,在这种情况下,您正在使用通配符 `*.xyz`,因此每个 `xyz` 文件都将被处理,所以如果您想按文件执行操作,您需要使用变量扩展。
@echo off
for %%f in (*.abc) do (
abc2xyz "%%~f"
procxyz "%%~nf.xyz"
)
请注意,第二个命令周围的双引号很重要,如果您的文件名中有空格,您的文件将无法被处理。
您可以通过运行以下命令来测试实际结果,不需要修改它们:
@echo off
for %%f in (*.abc) do (
echo "%%~f"
echo "%%~nf.xyz"
)
您可以通过在 `cmd` 中运行 `for /?`,然后向下滚动并阅读 `substitution` 部分来了解有关变量扩展的更多信息。
<details>
<summary>英文:</summary>
Each time you enter the loop, each command is executed, in this case, you are using a wildcard `*.xyz` and therefore each `xyz` file will be processed, so if you want to do it per file, you need to use variable expansion.
@echo off
for %%f in (*.abc) do (
abc2xyz "%%~f"
procxyz "%%~nf.xyz"
)
Note, the surrounding double quotes on the second command is important, if your file has a space, your file will not be processed.
You can test the actual results, without modifying them, by running the following:
@echo off
for %%f in (*.abc) do (
echo "%%~f"
echo "%%~nf.xyz"
)
You can read about variable expansion by running, from `for /?` from `cmd`, then scroll down and read the `substitution` section.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论