Shell-Script

如何比較同一目錄中對應的多個文件

  • August 5, 2021

嗨所以我有一個文件夾/mell/908,其中包含如下文件:

cf-mell-pos-908-tcg-4619e.txt
cf-mell-pos-908-tcw-4619e.txt
cf-mell-pos-908-usc-4619e.txt
cf-mell-pos-908-wi_board-4619e.txt
copper_qnt
tcg_mell_upload_lx.txt
tcw_mell_upload_lx.txt
usc_mell_upload_lx.txt
wi_board_mell_upload_lx.txt

有沒有辦法可以使用diff命令來比較相應的文件

  • cf-mell-pos-908-tcg-4619e.txttcg_mell_upload_lx.txt
  • cf-mell-pos-908-tcw-4619e.txttcw_mell_upload_lx.txt

等等,而不必diff手動一對一地手動?我正在執行一個Linux系統。

我建議使用此選項,假設每對文件中匹配的字元串始終位於同一位置:

# loop over the files that start with 'cf-'
for f in cf-*.txt; do
 # extract the unique "code", e.g 'tcg'
 code=$(echo "$f" | cut -d'-' -f5)

 # match the looped file with the one that starts with the "code"
 echo "diff" *"-${code}"* "${code}"*.txt

 # perform your commands, in this case I use an `echo` to show
 # how the command `diff` will be executed
done

diff cf-mell-pos-908-tcg-4619e.txt tcg_mell_upload_lx.txt
diff cf-mell-pos-908-tcw-4619e.txt tcw_mell_upload_lx.txt
diff cf-mell-pos-908-usc-4619e.txt usc_mell_upload_lx.txt
diff cf-mell-pos-908-wi_board-4619e.txt wi_board_mell_upload_lx.txt

引用自:https://unix.stackexchange.com/questions/663343