批处理:对于名称中带有符号的文件问题的循环
Batch: for loop on files issue with symbol in name
为什么这个 for 循环不适用于带有“!”的文件?在文件名中?我怎样才能让它识别带有“!”的文件?或其他可能不起作用的符号。
@Echo off
SETLOCAL EnableExtensions EnableDelayedExpansion
set my_dir=C:\Test
set my_ext=txt
cd /d !my_dir!
for %%F in ("*.!my_ext!") do (
for /F "tokens=1,* delims=|" %%K in ('
forfiles /M "%%~F" /C "cmd /C echo @path^|@ext"
') do (
echo "%%~K": %%L
set list=!list!%%~K;
)
)
我收到了这样的返回消息,带有 !输出中缺失。
ERROR: Files of type "C:\Test\My file name has an explanation point here.txt" not found.
下面是一个可能对您有用的示例:
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "my_dir=C:\Test"
Set "my_ext=txt"
CD /D "%my_dir%" 2> NUL || GoTo :EOF
Set "list="
For %%G In ("*.%my_ext%") Do (Echo "%%~fG"^|%%~xG
If Not Defined list (Set "list=%%~fG") Else (
For /F "Tokens=1*Delims==" %%H In ('Set list'
) Do Set "list=%%I;%%~fG"))
SetLocal EnableDelayedExpansion
Echo(!list!
EndLocal
Pause
如果您希望每个文件路径都被双引号括起来,那么您只需要做一些小改动:
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "my_dir=C:\Test"
Set "my_ext=txt"
CD /D "%my_dir%" 2> NUL || GoTo :EOF
Set "list="
For %%G In ("*.%my_ext%") Do (Echo "%%~fG"^|%%~xG
If Not Defined list (Set "list="%%~fG"") Else (
For /F "Tokens=1*Delims==" %%H In ('Set list'
) Do Set "list=%%I;"%%~fG""))
SetLocal EnableDelayedExpansion
Echo(!list!
EndLocal
Pause
请务必注意,尤其是因为您为每个路径都使用了完整路径,所以用户定义的环境变量的大小有 32767 个字符的限制。这意味着根据 %my_dir%
中匹配文件的数量,您可能会超过该最大值。在这两个示例中,您显然可以删除 Echo "%%~fG"^|%%~xG
部分,如果您真的不需要它。
为什么这个 for 循环不适用于带有“!”的文件?在文件名中?我怎样才能让它识别带有“!”的文件?或其他可能不起作用的符号。
@Echo off
SETLOCAL EnableExtensions EnableDelayedExpansion
set my_dir=C:\Test
set my_ext=txt
cd /d !my_dir!
for %%F in ("*.!my_ext!") do (
for /F "tokens=1,* delims=|" %%K in ('
forfiles /M "%%~F" /C "cmd /C echo @path^|@ext"
') do (
echo "%%~K": %%L
set list=!list!%%~K;
)
)
我收到了这样的返回消息,带有 !输出中缺失。
ERROR: Files of type "C:\Test\My file name has an explanation point here.txt" not found.
下面是一个可能对您有用的示例:
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "my_dir=C:\Test"
Set "my_ext=txt"
CD /D "%my_dir%" 2> NUL || GoTo :EOF
Set "list="
For %%G In ("*.%my_ext%") Do (Echo "%%~fG"^|%%~xG
If Not Defined list (Set "list=%%~fG") Else (
For /F "Tokens=1*Delims==" %%H In ('Set list'
) Do Set "list=%%I;%%~fG"))
SetLocal EnableDelayedExpansion
Echo(!list!
EndLocal
Pause
如果您希望每个文件路径都被双引号括起来,那么您只需要做一些小改动:
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "my_dir=C:\Test"
Set "my_ext=txt"
CD /D "%my_dir%" 2> NUL || GoTo :EOF
Set "list="
For %%G In ("*.%my_ext%") Do (Echo "%%~fG"^|%%~xG
If Not Defined list (Set "list="%%~fG"") Else (
For /F "Tokens=1*Delims==" %%H In ('Set list'
) Do Set "list=%%I;"%%~fG""))
SetLocal EnableDelayedExpansion
Echo(!list!
EndLocal
Pause
请务必注意,尤其是因为您为每个路径都使用了完整路径,所以用户定义的环境变量的大小有 32767 个字符的限制。这意味着根据 %my_dir%
中匹配文件的数量,您可能会超过该最大值。在这两个示例中,您显然可以删除 Echo "%%~fG"^|%%~xG
部分,如果您真的不需要它。