这里是我的解决方案,它重命名文件在dir1中根据文件大小。
DIR1的内容:
-rw-r--r-- 1 haiv staff 10 Aug 16 13:18 file1.txt
-rw-r--r-- 1 haiv staff 20 Aug 16 13:18 file2.txt
-rw-r--r-- 1 haiv staff 30 Aug 16 13:18 file3.txt
-rw-r--r-- 1 haiv staff 205 Aug 16 13:18 file4.txt
(注:第五列存储的文件大小。)和DIR2的内容:
-rw-r--r-- 1 haiv staff 30 Aug 16 13:18 doc.txt
-rw-r--r-- 1 haiv staff 205 Aug 16 13:18 dopey.txt
-rw-r--r-- 1 haiv staff 20 Aug 16 13:18 grumpy.txt
-rw-r--r-- 1 haiv staff 10 Aug 16 13:18 happy.txt
创建一个文件调用〜/ rename.awk(是的从主目录,以避免污染要么DIR1或DIR2):
/^total/ {next} # Skip the first line (which contains the total, of ls -l)
{
if (name[$5] == "") {
name[$5] = $NF
print "# File of size", $5, "should be named", $NF
} else {
printf "mv '%s' '%s'\n", $NF, name[$5]
}
}
现在,cd到DIR1(如果你想重命名Dir1中的文件),并发出以下命令:
$ awk -f ~/rename.awk <(ls -l ../dir2) <(ls -l)
输出:
# File of size 30 should be named doc.txt
# File of size 205 should be named dopey.txt
# File of size 20 should be named grumpy.txt
# File of size 10 should be named happy.txt
mv 'file1.txt' 'happy.txt'
mv 'file2.txt' 'grumpy.txt'
mv 'file3.txt' 'doc.txt'
mv 'file4.txt' 'dopey.txt'
一旦你对结果满意,管上面的命令SH执行的更改:
$ awk -f ~/rename.awk <(ls -l ../dir2) <(ls -l) | sh
注:
- 没有保障针对相同大小的文件。为此,wonk0提供的MD5解决方案效果更好。
- 请在提交之前检查输出。更改是永久性的。
这是一个很好的答案,但是,你可以使用md5_file($文件),而不是MD5(的file_get_contents($文件)) – Landon
我以为这存在,但说实话,我是懒得寻找到手动;)顺便说一句,当然没有必要建立2个数组 – wonk0