简单的 bash 脚本将文件名中的空格更改为下划线

发布于 2024-11-25 15:41:20 字数 220 浏览 4 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

╰ゝ天使的微笑 2024-12-02 15:41:20

您需要在变量和命令替换周围使用双引号,以防止文件名中的空格被误认为参数分隔符。另外,您不需要 sed,因为 bash 可以自行进行字符替换:

mv "$1" "${1// /_}"

编辑:我还发生了一些事情。首先,如果已经存在带有下划线(“a_e_i”或其他)的文件,您确实应该使用 mv -i 。其次,这只适用于简单的文件名——如果你给它一个封闭目录中带有空格的文件路径(例如“foo bar/baz quux/ae i”),它会尝试将其重命名为空格转换后的目录,这并不存在,导致喜剧。所以这里有一个建议的更好版本:

mv -i "$1" "$(dirname "$1")/$(basename "${1// /_}")"

顺便说一句,其他答案在用下划线替换空格后省略了文件名上的双引号——这并不完全安全,因为还有其他有趣的字符可能仍然会引起麻烦。规则 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:

mv "$1" "${1// /_}"

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:

mv -i "$1" "$(dirname "$1")/$(basename "${1// /_}")"

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.

抹茶夏天i‖ 2024-12-02 15:41:20

试试这个 - 纯 bash:

mv "$1" ${1// /_}

try this - pure bash:

mv "$1" ${1// /_}
风轻花落早 2024-12-02 15:41:20

您的 $1 扩展为 aei,然后将其用作 mv 的前三个参数,因此您的调用变为

mv a e i a_e_i

这就是您收到错误消息的原因。
要解决这个问题,您所要做的就是引用 $1:

mv "$1" $(echo "$1" | sed s:\ :_:g)

Your $1 expands to a e i, which is then used as the first three arguments to mv, so your call becomes

mv a e i a_e_i

This is the reason for the error message you get.
To fix this, all you have to do is quote the $1:

mv "$1" $(echo "$1" | sed s:\ :_:g)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文