linux bash中遞歸尋找一個目錄中的檔案是否存在於另一個目錄中並且列印存在或不存在

linux bash中遞歸尋找一個目錄中的檔案是否存在於另一個目錄中並且列印存在或不存在

linux bash中遞歸尋找一個目錄中的檔案是否存在於另一個目錄中並且列印存在或不存在

假設你有

  • pth1/dirA/file1 pth1/dirA/DirB/file2
  • pth2/dirA/file1 pth2/dirA/DirB/file3

我想要一份報告

file1 exists 
files2 dont exist in pth2
files3 dont exist in pth1

我發現該程式碼適用於兩個目錄的當前級別,但我無法使其遞歸工作取自這裡

pth1="/mntA/newpics";
pth2="/mntB/oldpics";
for file in "${pth1}"/*; do
    if [[ -f "${pth2}/${file##*/}" ]]; then
       echo "$file exists";
    fi
done

我怎樣才能在兩條路徑上遞歸工作?

答案1

我用另一種方​​法做到了。我找到一個目錄中的所有文件,剝離它們的路徑,然後我可以將結果保存在兩個不同的文件中並將它們與 meld 或其他程式進行比較,或者我可以直接與 meld 比較查找結果。

請注意,我對文件進行排序並僅選擇唯一的文件,而不選擇結果中的重複文件。另外,我只對檔案名稱以「jpg」副檔名結尾的檔案感興趣。

pth1="/mnt/oldfiles";
pth2="/mnt/newfiles";

進而

(find "${pth1}"/ -exec basename {} \; | grep "jpg$" | sort | uniq )  > a.txt;
(find "${pth2}"/ -exec basename {} \; | grep "jpg$" | sort | uniq )  > b.txt;
meld a.txt b.txt

或者直接

meld <(find "${pth1}"/ -exec basename {} \; | grep "jpg$" | sort | uniq )  <(find "${pth2}"/ -exec basename {} \; | grep "jpg$" | sort | uniq )

更新:如果一個目錄比其他目錄大得多,則直接命令不起作用(MILD 在兩個命令都未完成的情況下開啟)。

答案2

目前還不太清楚你想要什麼,但我認為這可以做到。此命令將 下的所有檔案/path/1與 下的所有檔案進行比較/path/2,檢查是否存在且相等。

diff --brief --recursive /path/1 /path/2

工作範例

# Create some files
mkdir -p 1/{x,y} 2/{x,z}
touch 1/{x,y}/file1
date | tee 2/x/file1 >2/z/date

# Show what we have
tree 1 2
1
├── x
│   └── file1
└── y
    └── file1
2
├── x
│   └── file1
└── z
    └── date
4 directories, 4 files

# Compare the two directory trees
diff --brief --recursive 1 2
Files 1/x/file1 and 2/x/file1 differ
Only in 1: y
Only in 2: z

相關內容