這裏是我的解決方案,它重命名文件在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