比較文件並選擇較大的文件

比較文件並選擇較大的文件

有兩個目錄,有很多檔案。這些文件的名稱始終匹配,但大小並不總是匹配。例如:

/dir1
|-file1 (1 MB)
|-file2 (2 MB)
|-file3 (3 MB)

/dir2
|-file1 (1 KB)
|-file2 (2 MB)
|-file3 (10 MB)

如您所見,文件名匹配,但文件大小僅在 file2 中匹配。如何比較這兩個目錄中的檔案並僅選擇較大的檔案?範例中的輸出必須是“/dir2/file3”。

如果 dir1 中的檔案比 dir2 中同名的檔案大,則不執行任何操作。我只對 dir2 中比 dir1 中的文件大的文件感興趣

我寫了一個腳本,但只有在 dir2 中找到一個更大的檔案時才有效。

#!/bin/bash
diff -q $1 $2 | awk '{ print $2,$4 }' > tempfile.txt
A=`cat tempfile.txt | cut -d ' ' -f 1`
B=`ls -s $A | cut -d ' ' -f 1`
C=`cat tempfile.txt | cut -d ' ' -f 2`
D=`ls -s $C | cut -d ' ' -f 1`
if [ "$D" -gt "$B" ]; then
 echo $C
fi

答案1

#!/usr/bin/env zsh

zmodload -F zsh/stat b:zstat

for file2 in dir2/*(.); do
    file1="dir1/${file2##*/}"

    if [ -f "$file1" ] &&
       [ "$( zstat +size "$file2" )" -gt "$( zstat +size "$file1" )" ]
    then
        printf '%s is bigger than %s\n' "$file2" "$file1"
    fi
done

這是一個zshshell 腳本,它使用內建命令zstat來便攜式獲取檔案大小。

該腳本將循環遍歷目錄中具有非隱藏名稱的所有常規檔案dir2。對於其中的每個文件,dir2將為 中的文件建構相應的路徑名dir1。如果檔案dir1存在且是常規檔案(或常規檔案的符號連結),則比較兩個檔案的大小。如果輸入的檔案dir2明顯較大,則會輸出一則短訊息。

此模式dir2/*(.)將僅符合目錄中常規檔案的非隱藏名稱dir2。這(.)是一個zsh特定的修飾符,*使其僅匹配常規文件。

此表達式"dir1/${file2##*/}"將擴展為以 開頭並包含先前所有內容(包括最後刪除的內容dir1/)的值的路徑名。這可以更改為.$file2/"dir1/$( basename "$file2" )"

答案2

#!/bin/bash

get_attr() {
    # pass '%f' to $2 to get file name(s) or '%s' to get file size(s)
    find "$1" -maxdepth 1 -type f -printf "$2\n"
}

while read -r file
do
    (( $(get_attr "dir2/$file" '%s') > $(get_attr "dir1/$file" '%s') )) \
        && realpath -e "dir2/$file"
done < <(get_attr dir2 '%f')

這假設 中的所有文件dir2與 中的文件具有相同的名稱dir1,如上所述。

realpath列印文件的絕對路徑。

該腳本還比較隱藏檔案(以 開頭的檔案.)。

相關內容