windows-7 - DOS 批处理 : Getting partial file names

标签 windows-7 batch-file 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。任何帮助将不胜感激,谢谢。

最佳答案

Environment variable expansion occurs when the command is read ,因此当读取 for 时,您的 %fileName:~-4% 会被评估,这是 Set之前> 已执行。使用延迟扩展。

@ECHO OFF
SETLOCAL SETDELAYEDEXPANSION
for /r C:\Users\userName\Desktop\testFolder %%g in (*) do (
   Set fileName=%%~ng
   echo !fileName:~-4!
)

另请注意,Set 命令中的空格很重要。使用该空格,您创建了一个名为 fileName 的变量,其尾随空格。

关于windows-7 - DOS 批处理 : Getting partial file names,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7811322/

相关文章:

windows-7 - 如何在快捷方式上设置 AppUserModelID?

.net - 如何使WPF窗口在任务栏上闪烁?

c# - 如何获取应用程序的AppData VirtualStore路径?

c - DOS/4GW fatal error (1307) : not enough memory

windows - 如何调试 .BAT 脚本?

powershell - Powershell函数返回字符串,但客户端获取数组

windows - 从 .bat 文件执行 PowerShell 脚本时出错

batch-file - 如何解决这个 : Execution of batch script terminates after a specific command but runs fine when commandd is executed manually

windows - CMD: Bat to Exe Converter - 临时目录问题

command-line - 使用批处理文件打开一系列文件中的一个