简单的 bash 脚本将文件名中的空格更改为下划线
mv $1 $(echo $1 | sed s:\ :_:g)
这是一个简单的脚本,它重命名作为参数传递的文件,将空格替换为下划线。但是,当我尝试将文件“ae i”重命名为“a_e_i”时,它会返回以下错误:
./spc2und a\ e\ i
mv: target `a_e_i' is not a directory
mv $1 $(echo $1 | sed s:\ :_:g)
It's a simple script that renames the file passed as argument, exchanging spaces to underlines. However, when I try to rename the file "a e i" to "a_e_i" for example, it returns the following error:
./spc2und a\ e\ i
mv: target `a_e_i' is not a directory
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要在变量和命令替换周围使用双引号,以防止文件名中的空格被误认为参数分隔符。另外,您不需要 sed,因为 bash 可以自行进行字符替换:
编辑:我还发生了一些事情。首先,如果已经存在带有下划线(“a_e_i”或其他)的文件,您确实应该使用
mv -i
。其次,这只适用于简单的文件名——如果你给它一个封闭目录中带有空格的文件路径(例如“foo bar/baz quux/ae i”),它会尝试将其重命名为空格转换后的目录,这并不存在,导致喜剧。所以这里有一个建议的更好版本:顺便说一句,其他答案在用下划线替换空格后省略了文件名上的双引号——这并不完全安全,因为还有其他有趣的字符可能仍然会引起麻烦。规则 1:如有疑问,为了安全起见,请将其用双引号引起来。规则2:保持怀疑。
You need double-quotes around the variables and command substitution to prevent spaces in the filename from being mistaken for argument separators. Also, you don't need sed, since bash can do character replacement by itself:
Edit: a few more things occurred to me. First, you really should use
mv -i
in case there's already a file with underscores ("a_e_i" or whatever). Second, this only works on simple filenames -- if you give it a file path with spaces in an enclosing directory, (e.g. "foo bar/baz quux/a e i"), it tries to rename it into a directory with the spaces converted, which doesn't exist, leading to comedy. So here's a proposed better version:BTW, the other answers leave off the double-quotes on the filename after replacing spaces with underscores -- this isn't entirely safe, as there are other funny characters that might still cause trouble. Rule 1: when in doubt, wrap it in double-quotes for safety. Rule 2: be in doubt.
试试这个 - 纯 bash:
try this - pure bash:
您的 $1 扩展为 aei,然后将其用作 mv 的前三个参数,因此您的调用变为
这就是您收到错误消息的原因。
要解决这个问题,您所要做的就是引用 $1:
Your $1 expands to a e i, which is then used as the first three arguments to mv, so your call becomes
This is the reason for the error message you get.
To fix this, all you have to do is quote the $1: