gpt4 book ai didi

linux - 如何使用 bash 脚本替换文件名中的空格

转载 作者:IT老高 更新时间:2023-10-28 12:17:55 26 4
gpt4 key购买 nike

谁能推荐一个安全的解决方案,从给定的根目录开始,用下划线递归替换文件和目录名称中的空格?例如:

$ tree
.
|-- a dir
| `-- file with spaces.txt
`-- b dir
|-- another file with spaces.txt
`-- yet another file with spaces.pdf

变成:

$ tree
.
|-- a_dir
| `-- file_with_spaces.txt
`-- b_dir
|-- another_file_with_spaces.txt
`-- yet_another_file_with_spaces.pdf

最佳答案

我用:

for f in *\ *; do mv "$f" "${f// /_}"; done

虽然它不是递归的,但它非常快速和简单。我敢肯定这里有人可以将其更新为递归。

${f///_} 部分利用 bash 的参数扩展机制将参数中的模式替换为提供的字符串。相关语法是 ${parameter/pattern/string}。见:https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.htmlhttp://wiki.bash-hackers.org/syntax/pe .

关于linux - 如何使用 bash 脚本替换文件名中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2709458/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com