使用 find 和 xargs 复制具有基于 md5 的目标名称的文件

使用 find 和 xargs 复制具有基于 md5 的目标名称的文件

我有一个目录树,其中有很多.dat文件,其中许多包含特殊字符。它们由另一个只能处理包含 ascii 字符的文件的进程使用。

我的想法是对find所有文件,根据md5文件路径的哈希值构建一个新文件名,并将它们复制到一个新目录(它们不是很大,我可能不会更改原始目录)。

这是我尝试过的

find dat -type f -name "*.dat" -print0|xargs -0 -I file cp 'file' "datnew/$(echo file|md5).dat"

不幸的是,它只构建一个散列,并将所有文件复制到该输出文件名:

$ touch dat/foo.dat
$ touch dat/bar.dat
$ find dat -type f -name "*.dat" -print0|xargs -0 -I file cp 'file' "datnew/$(echo file|md5).dat"
$ ls datnew
bbe02f946d5455d74616fc9777557c22.dat

你能告诉我我的错误是什么吗?难道是我使用xargs方式不对?

答案1

由于file不会$( echo $file | md5 )被解释,您需要一个解决方法。

一种可能性是简单地将其输入while循环并读取每个输出 - 在这种情况下最好xargs整体跳过

find ... | while read file ; do cp "$file" "datnew/$( echo "$file" | md5 )" ; done

要使用它,-print0请使用以下命令将空字符替换为换行符tr

find ... -print0 | tr '\000\' '\n' | while read ; do ... ; done

相关内容