将带有空格的文件重命名为所有子类别中的下划线
Rename files with spaces to underscore in all subcategories
我有类别/产品/和子类别。我需要一个单行命令来删除名称中的空格到下划线,如果它的 2 个空格只放置 1 个下划线。重命名命令在此服务器上不起作用。
我一直在使用 for file in *; do mv "$file" echo $file | tr ' ' '_' ; done
但它不适用于我有很多的子类别,另外如果有 2 个空格,此命令将生成 2 个下划线,我需要不同的。
请指教
更新:
找到 OP(如此处所述:) a more reliable way to strip spaces from files, which he notes here: https://unix.stackexchange.com/a/223185 :
find -name "* *" -print0 | sort -rz | \ while read -d $'[=20=]' f; do mv
-v "$f" "$(dirname "$f")/$(basename "${f// /_}")"; done
原始答案(如果使用 bash
和 GNU 的兼容版本,可能会帮助其他人作为重命名文件的框架sed
可以使用 find
和 sed
吗?
编辑:
作为一个班轮:
find "$(pwd)" -type f -print0 | while IFS= read -d '' file ; do newfile="$(echo "$file" | sed -E 's/\s+/_/g')" ; newcmd='mv -v "'"$file"'" "'"$newfile"'"' ; echo "$newcmd" ; done
find "$(pwd)" -type f -print0 | while IFS= read -d '' file
do
newfile="$(echo "$file" | sed -E 's/\s+/_/g')"
newcmd='mv -v "'"$file"'" "'"$newfile"'"'
#for test run use echo
echo "$newcmd"
#for real run use eval
eval "$newcmd"
done
我发现在文件名中进行搜索和替换的一般风格是可靠的。有几个原因我不只是使用替换而且我不记得它们,但这里的关键点是;
- 你不受
$IFS
变量的摆布
- 非常奇怪的文件名将被括在引号中并适合执行
- 您没有直接对 glob 扩展执行
mv
命令
sed
中的\s+
将根据您的需要替换一个或多个空格
感谢@Barmar。我使用了答案 https://unix.stackexchange.com/questions/223182/how-to-replace-spaces-in-all-file-names-with-underscore-in-linux-using-shell-scr/223185#223185
中的命令
只要确保它在两行中
我有类别/产品/和子类别。我需要一个单行命令来删除名称中的空格到下划线,如果它的 2 个空格只放置 1 个下划线。重命名命令在此服务器上不起作用。
我一直在使用 for file in *; do mv "$file" echo $file | tr ' ' '_' ; done
但它不适用于我有很多的子类别,另外如果有 2 个空格,此命令将生成 2 个下划线,我需要不同的。
请指教
更新:
找到 OP(如此处所述:
find -name "* *" -print0 | sort -rz | \ while read -d $'[=20=]' f; do mv -v "$f" "$(dirname "$f")/$(basename "${f// /_}")"; done
原始答案(如果使用 bash
和 GNU 的兼容版本,可能会帮助其他人作为重命名文件的框架sed
可以使用 find
和 sed
吗?
编辑:
作为一个班轮:
find "$(pwd)" -type f -print0 | while IFS= read -d '' file ; do newfile="$(echo "$file" | sed -E 's/\s+/_/g')" ; newcmd='mv -v "'"$file"'" "'"$newfile"'"' ; echo "$newcmd" ; done
find "$(pwd)" -type f -print0 | while IFS= read -d '' file
do
newfile="$(echo "$file" | sed -E 's/\s+/_/g')"
newcmd='mv -v "'"$file"'" "'"$newfile"'"'
#for test run use echo
echo "$newcmd"
#for real run use eval
eval "$newcmd"
done
我发现在文件名中进行搜索和替换的一般风格是可靠的。有几个原因我不只是使用替换而且我不记得它们,但这里的关键点是;
- 你不受
$IFS
变量的摆布 - 非常奇怪的文件名将被括在引号中并适合执行
- 您没有直接对 glob 扩展执行
mv
命令 sed
中的\s+
将根据您的需要替换一个或多个空格
感谢@Barmar。我使用了答案 https://unix.stackexchange.com/questions/223182/how-to-replace-spaces-in-all-file-names-with-underscore-in-linux-using-shell-scr/223185#223185
中的命令只要确保它在两行中