首页 > 解决方案 > 为什么 zsh `for` 循环错误并带有 `command not found: filename.txt`?尽管 filename.txt 是参数而不是命令

问题描述

以下 shell 历史显示了两次重命名文件的尝试,第二次尝试成功。但第一次尝试没有,我不知道为什么......

❯ ls
step-10.txt  step-12.txt  step-14.txt  step-16.txt  step-18.txt  step-1.txt  step-3.txt  step-5.txt  step-7.txt  step-9.txt
step-11.txt  step-13.txt  step-15.txt  step-17.txt  step-19.txt  step-2.txt  step-4.txt  step-6.txt  step-8.txt
❯ for f in *.txt; do
newname=$(echo $f | sed 's/txt/md/')\
mv $f $newname
done
zsh: command not found: step-10.txt
zsh: command not found: step-11.txt
zsh: command not found: step-12.txt
zsh: command not found: step-13.txt
zsh: command not found: step-14.txt
zsh: command not found: step-15.txt
zsh: command not found: step-16.txt
zsh: command not found: step-17.txt
zsh: command not found: step-18.txt
zsh: command not found: step-19.txt
zsh: command not found: step-1.txt
zsh: command not found: step-2.txt
zsh: command not found: step-3.txt
zsh: command not found: step-4.txt
zsh: command not found: step-5.txt
zsh: command not found: step-6.txt
zsh: command not found: step-7.txt
zsh: command not found: step-8.txt
zsh: command not found: step-9.txt
↵ Error. Exit status 127.
❯ for f in *.txt; do
mv $f $(echo $f | sed 's/txt/md/')
done
❯ ls
step-10.md  step-12.md  step-14.md  step-16.md  step-18.md  step-1.md  step-3.md  step-5.md  step-7.md  step-9.md
step-11.md  step-13.md  step-15.md  step-17.md  step-19.md  step-2.md  step-4.md  step-6.md  step-8.md

为什么当我将它$(echo $f | sed 's/txt/md/')放在行上时它会起作用,mv但当它被分配给变量时却不起作用?为什么它说command not found: $f当我的循环$f作为命令的参数提供时mv

标签: shellzsh

解决方案


那个反斜杠意味着它正在评估

newname=$(echo $f | sed 's/txt/md/')mv $f $newname

这当然将文件名视为要运行的命令的名称(mvnewname变量的一部分)

你根本不需要sed这里;只需使用参数扩展:

for f in *.txt; do
    mv "$f" "${f/%txt/md}"
done

还有几个不同的程序(rename取决于操作系统)可以批量重命名文件;检查您已安装和使用的手册页(如果有)。prenamerename.ul


推荐阅读