gpt4 book ai didi

linux - bash 重命名空间 - 也做子文件和文件夹

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:30:38 25 4
gpt4 key购买 nike

我有这个脚本只执行父文件夹,它不会重命名子文件夹和文件 - 我希望它能用 _ 去除所有非数字。

#!/bin/bash
for f in *
do
new="${f// /_}"
if [ "$new" != "$f" ]
then
if [ -e "$new" ]
then
echo not renaming \""$f"\" because \""$new"\" already exists
else
echo moving "$f" to "$new"
mv "$f" "$new"
fi
fi
done

最佳答案

获取文件和目录列表:

要对文件进行递归操作,与 glob 相比,使用 find 是更好的解决方案。我建议在开始操作文件名之前将其填充到一个 bash 数组中。此外,我认为一次一步执行此操作,先是目录,然后是文件,这将是谨慎的做法。您不想重命名目录,然后在重命名文件时发现该文件不存在。出于同样的原因,脚本在文件系统层次结构的更深层次上工作也很重要(因此使用下面的 sort)。

对列表进行操作:

获得列表后,您可以调用一个通用的 shell 函数来对文件或目录名称进行规范化和重命名。请注意正确引用名称以获得所需内容的重要性。这是非常重要的,因为 bash(或与此相关的任何 shell)在解析命令行时使用空格作为单词边界。

脚本:

以下脚本(在下面的示例输出中名为 ./rename_spaces.bash)应该执行您想要的操作。要添加您自己的怪异字符,请将它们添加到 weirdchars 变量中。请注意,您需要对字符进行适当的转义(例如,单引号已被转义)。如果新文件名存在,脚本将跳过并显示一条消息。这也意味着它将打印琐碎的重命名消息(原始名称中没有奇怪字符的文件名)。这对某些人来说可能很烦人(例如我 :-p)

#!/bin/bash

# set -o xtrace # uncomment for debugging

declare weirdchars=" &\'"

function normalise_and_rename() {
declare -a list=("${!1}")
for fileordir in "${list[@]}";
do
newname="${fileordir//[${weirdchars}]/_}"
[[ ! -a "$newname" ]] && \
mv "$fileordir" "$newname" || \
echo "Skipping existing file, $newname."
done
}

declare -a dirs files

while IFS= read -r -d '' dir; do
dirs+=("$dir")
done < <(find -type d -print0 | sort -z)

normalise_and_rename dirs[@]

while IFS= read -r -d '' file; do
files+=("$file")
done < <(find -type f -print0 | sort -z)

normalise_and_rename files[@]

这是一个示例输出,其中包含一个目录树,其中包含在运行上述脚本之前和之后名称中带有空格的目录和文件。

$ tree
.
├── dir1
│ ├── subdir1\ with\ spaces
│ │ └── file1
│ └── subdir2\ with\ spaces&weird\ chars'
│ └── file2
├── dir2
│ ├── subdir1\ with\ spaces
│ │ └── file1\ with\ space
│ └── subdir2\ with\ spaces
│ └── file2\ with\ space
├── dir3
│ ├── subdir1
│ │ └── file1
│ ├── subdir2
│ │ └── file2
│ └── subdir3
│ └── file3
└── rename_spaces.bash

10 directories, 8 files
$ ./rename_spaces.bash
$ tree
.
├── dir1
│ ├── subdir1_with_spaces
│ │ └── file1
│ └── subdir2_with_spaces_weird_chars_
│ └── file2
├── dir2
│ ├── subdir1_with_spaces
│ │ └── file1_with_space
│ └── subdir2_with_spaces
│ └── file2_with_space
├── dir3
│ ├── subdir1
│ │ └── file1
│ ├── subdir2
│ │ └── file2
│ └── subdir3
│ └── file3
└── rename_spaces.bash

10 directories, 8 files

注意:实现脚本以对任何非字母数字“做正确的事”似乎很重要。例如,我不确定如何处理文件或目录名称中的点或预先存在的下划线或其他“常规”允许的字符。

以通用方式识别不需要的/特殊字符也是一个问题。在国际语言环境下就更复杂了。我不知道有什么简单的方法可以说“只允许使用英文字母表中的数字或字符”。如果有人有想法,请继续发布答案。

关于linux - bash 重命名空间 - 也做子文件和文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11622018/

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