DOS 批处理:获取部分文件名
我正在尝试为 Windows 7 环境编写这个小批处理文件。它应该遍历目录并回显文件名的最后四个字符。到目前为止,我已经得到:
@ECHO OFF
SETLOCAL
for /r C:\Users\userName\Desktop\testFolder %%g in (*) do (
Set fileName = %%~ng
echo %fileName:~-4%
)
对于 testFolder 中的每个文件,所有回显的都是“~-4”一次。我不知道出了什么问题,但我不太熟悉批处理文件或 dos。任何帮助将不胜感激,谢谢。
I've got this little batch file I'm trying to write for a Windows 7 environment. It's supposed to go through a directory and echo the last four characters of the file names. So far I've got:
@ECHO OFF
SETLOCAL
for /r C:\Users\userName\Desktop\testFolder %%g in (*) do (
Set fileName = %%~ng
echo %fileName:~-4%
)
And all that is echoed out is "~-4" once for each file in testFolder. I can't figure out what's wrong, but then I'm not very well versed in batch files or dos. Any help would be appreciated, thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
读取命令时会发生环境变量扩展,因此您的
%fileName:~-4%
在读取for
时进行评估,这是在执行Set
之前。使用延迟扩展。另请注意,
Set
命令中的空格很重要。使用该空格,您创建了一个名为fileName
的变量,并带有尾随空格。Environment variable expansion occurs when the command is read, so your
%fileName:~-4%
is evaulated when thefor
is read, which is before theSet
is performed. Use delayed expansion.Note also that spaces are significant in the
Set
command. With the space, you created a variable calledfileName
with a trailing space.