shell - 为什么 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
?
解决方案
那个反斜杠意味着它正在评估
newname=$(echo $f | sed 's/txt/md/')mv $f $newname
这当然将文件名视为要运行的命令的名称(mv是newname
变量的一部分)
你根本不需要sed
这里;只需使用参数扩展:
for f in *.txt; do
mv "$f" "${f/%txt/md}"
done
还有几个不同的程序(rename
取决于操作系统)可以批量重命名文件;检查您已安装和使用的手册页(如果有)。prename
rename.ul
推荐阅读
- windows - Octave:隐藏复杂绘图的窗口;改为打印到文件
- windows - 有没有办法在有气隙的窗户机器上使用它?
- flutter - 实现 InheritedWidget 及其超级构造函数的类的问题
- authentication - 如何使用 Authentication 插件实现 CakePHP ACL 插件
- remote-access - PsExec - 系统无法访问该文件
- mobile - 手机 USSD 没有发送字母字符的选项
- node.js - 在 TypeORM 和 NestJS 中连接表时出错
- python - 从资源管理器中选择一个文件并将他的名字插入 python kivy 应用程序
- linux - 如何构建带有-generic 后缀的linux内核?
- matlab - Matlab上两个符号数组的卷积