如何在命令列中刪除目錄B中目錄A中的符合檔案?

如何在命令列中刪除目錄B中目錄A中的符合檔案?

我的目錄中有一些重複的文件AB如何B在 bash 中使用文件名刪除重複的文件A

如何在其他 shell 中執行此操作是一個值得歡迎的獎勵。

答案1

單程:

#!/bin/bash
cd ~/B
for file in ~/A/*
do
    file1=$(basename "$file")
    [ -f "$file1" ] && { echo "deleting $file1 "; rm -- "$file1"; }
done

答案2

在一行中

grep -f <(ls "A") <(ls "B") | xargs -I'{}' rm "B/{}"

但它的工作原理僅取決於檔案名,並且可能會影響空子目錄。為了避免這種情況,find -type f -maxdepth 1請使用ls.

為了更安全地檢查,請使用@KasyA receiveie。

答案3

find /path/to/dirA -type f -exec cmp -s '{}' '/path/to/dirB/{}' \; -exec echo rm -v '/path/to/dirB/{}' \;

在測試中:

$ ls -1 /path/to/dirA
dupfile
file1inA

$ ls -1 /path/to/dirB
dupfile
file1inB

find /path/to/dirA -type f -exec cmp -s '{}' '/path/to/dirB/{}' \; -exec echo rm -v '/path/to/dirB/{}' \;
rm -v /path/to/dirB/./dupfile

注意:刪除echo用於空運行的。

答案4

cd B

ls ../
A
B

comm <(ls ../A) <(ls ./) -1 -2 -z | xargs -0 rm

comm顯示三列,

  1. file1(A) 特有的
  2. file2(B) 獨有的
  3. 兩者都存在

所以我們將第 1、2 列刪除-1 -2-z將使用 NULL 作為分隔符號。預設為“\n”換行符。

當處理管道和任意字串清單(如檔案名稱)時,NULL 分隔傳輸是安全的。

相關內容