如何在批处理文件中循环匹配通配符的文件
我有一组基本文件名,每个名称'f'都有两个文件,'f.in'和'f.out'。我想编写一个批处理文件(在Windows XP中),它遍历所有文件名,每个文件名都应:
- 显示基本名称" f"
- 对" f.in"执行操作
- 对" f.out"执行其他操作
除了搜索* .in(或者* .out)之外,我没有任何办法列出基本文件名。
解决方案
回答
如我所见,最简单的方法是使用for循环,该循环调用第二个批处理文件进行处理,并将第二个文件的基本名称传递给该文件。
根据for /?帮助,可以使用nifty〜n选项提取基本名称。因此,基本脚本将显示为:
for %%f in (*.in) do call process.cmd %%~nf
然后,在process.cmd中,假定%0包含基本名称并采取相应措施。例如:
echo The file is %0 copy %0.in %0.out ren %0.out monkeys_are_cool.txt
在一个脚本中可能有更好的方法来执行此操作,但是对于如何在批处理文件的单个for循环中提取多个命令,我一直有些困惑。
编辑:太棒了!我以某种方式错过了文档中的页面,该页面表明我们可以在FOR循环中执行多行块。我要走了,现在必须回去重写一些批处理文件...
回答
据我所记得,MS Server中通常使用一种称为forfiles的工具:
上面的链接包含帮助以及到Microsoft下载页面的链接。
回答
我们可以使用以下行来打印桌面的内容:
FOR %%I in (C:\windows\desktop\*.*) DO echo %%I
一旦有了%% I变量,就可以很容易地对其执行命令(只需用程序替换echo即可)
此外,FOR变量引用的替换已得到增强
现在,我们可以使用以下可选语法:
%~I - expands %I removing any surrounding quotes (") %~fI - expands %I to a fully qualified path name %~dI - expands %I to a drive letter only %~pI - expands %I to a path only (directory with \) %~nI - expands %I to a file name only %~xI - expands %I to a file extension only %~sI - expanded path contains short names only %~aI - expands %I to file attributes of file %~tI - expands %I to date/time of file %~zI - expands %I to size of file %~$PATH:I - searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string [https://ss64.com/nt/syntax-args.html][1]
在上面的例子中,%I
和PATH可以被其他有效的替换。
价值观。 %%语法以有效的FOR变量名终止。
选择大写的变量名,如%I
使其更易读且
避免与不区分大小写的修饰符混淆。
我们可以通过输入" FOR /?"来获得完整的文档。
回答
假设我们有两个程序来处理两个文件,process_in.exe和process_out.exe:
for %%f in (*.in) do ( echo %%~nf process_in "%%~nf.in" process_out "%%~nf.out" )
%%〜nf是替换修饰符,它将%f扩展为仅文件名。
请参阅https://technet.microsoft.com/zh-cn/library/bb490909.aspx(在页面中间)或者在下一个答案中的其他修饰符。
回答
在Nathans帖子上扩展。下面将在一个批处理文件中完成工作。
@echo off if %1.==Sub. goto %2 for %%f in (*.in) do call %0 Sub action %%~nf goto end :action echo The file is %3 copy %3.in %3.out ren %3.out monkeys_are_cool.txt :end