【发布时间】:2016-06-29 23:34:54
【问题描述】:
我需要一个 bash 脚本来递归地重命名带有空白扩展名的文件以在末尾附加 .txt。我找到了以下脚本,但我不知道如何使其递归:
#!/bin/sh
for file in *; do
test "${file%.*}" = "$file" && mv "$file" "$file".txt;
done
谢谢。
谢谢。
【问题讨论】:
我需要一个 bash 脚本来递归地重命名带有空白扩展名的文件以在末尾附加 .txt。我找到了以下脚本,但我不知道如何使其递归:
#!/bin/sh
for file in *; do
test "${file%.*}" = "$file" && mv "$file" "$file".txt;
done
谢谢。
谢谢。
【问题讨论】:
您可以将繁重的工作委托给find
$ find . -type f ! -name "*.*" -print0 | xargs -0 -I file mv file file.txt
assumption is without extension 意思是名称中没有句点。
【讨论】:
xargs 可以避免:find . -type f ! -name '*.*' -exec mv {} {}.txt \;。
如果您不介意使用递归函数,那么您可以在较旧的 Bash 版本中使用:
shopt -s nullglob
function add_extension
{
local -r dir=$1
local path base
for path in "$dir"/* ; do
base=${path##*/}
if [[ -f $path && $base != *.* ]] ; then
mv -- "$path" "$path.txt"
elif [[ -d $path && ! -L $path ]] ; then
add_extension "$path"
fi
done
return 0
}
add_extension .
mv -- 用于防止路径以连字符开头。
【讨论】: