用 bash 中内容的 MD5 哈希字符串替换文件的完整文件名
Replace the complete filenames for files with their MD5 hash string of the content in bash
问题:
我在一个文件夹里有一堆文件,我想把它们全部重命名为文件内容的md5。
我尝试了什么:
这是我试过的命令。
for i in $(find /home/admin/test -type f);do mv $i $(md5sum $i|cut -d" " -f 1);done
但是一段时间后失败并出现错误,只有一些文件被重命名,其余文件保持不变。
mv: missing destination file operand after /home/admin/test/help.txt
Try `mv --help' for more information.
实现是否正确?我在脚本中做错了什么吗?
通过使用 shell 提供的 glob 模式来简化事情,而不是使用像 find
这样的外部实用程序。另见 Why you don't read lines with "for"
在文件夹 /home/admin/test
中导航并执行以下操作就足够了
for file in *; do
[ -f "$file" ] || continue
md5sum -- "$file" | { read sum _; mv "$file" "$sum"; }
done
首先尝试使用 echo
代替 mv
检查一次文件是否按预期重命名。
要转到下面的子目录(我认为这也是您的要求),请启用 globstar
,这是 shell 提供的扩展全局选项之一,可以更深入
shopt -s globstar
for file in **/*; do
如果你想用它们的 md5 哈希递归重命名所有文件,你可以试试这个:
find /home/admin/test -type f -exec bash -c 'md5sum "" | while read s f; do mv "${f#*./}" "$(dirname ${f#*./})/$s"; done' _ {} \;
散列和文件名作为参数提供给 s
和 f
变量。 ${f#*./}
删除由 md5sum
和 find
命令添加的前缀。
请注意,如果某些文件具有完全相同的内容,最终将只有 1 个文件。
问题:
我在一个文件夹里有一堆文件,我想把它们全部重命名为文件内容的md5。
我尝试了什么:
这是我试过的命令。
for i in $(find /home/admin/test -type f);do mv $i $(md5sum $i|cut -d" " -f 1);done
但是一段时间后失败并出现错误,只有一些文件被重命名,其余文件保持不变。
mv: missing destination file operand after /home/admin/test/help.txt
Try `mv --help' for more information.
实现是否正确?我在脚本中做错了什么吗?
通过使用 shell 提供的 glob 模式来简化事情,而不是使用像 find
这样的外部实用程序。另见 Why you don't read lines with "for"
在文件夹 /home/admin/test
中导航并执行以下操作就足够了
for file in *; do
[ -f "$file" ] || continue
md5sum -- "$file" | { read sum _; mv "$file" "$sum"; }
done
首先尝试使用 echo
代替 mv
检查一次文件是否按预期重命名。
要转到下面的子目录(我认为这也是您的要求),请启用 globstar
,这是 shell 提供的扩展全局选项之一,可以更深入
shopt -s globstar
for file in **/*; do
如果你想用它们的 md5 哈希递归重命名所有文件,你可以试试这个:
find /home/admin/test -type f -exec bash -c 'md5sum "" | while read s f; do mv "${f#*./}" "$(dirname ${f#*./})/$s"; done' _ {} \;
散列和文件名作为参数提供给 s
和 f
变量。 ${f#*./}
删除由 md5sum
和 find
命令添加的前缀。
请注意,如果某些文件具有完全相同的内容,最终将只有 1 个文件。