2つの異なるファイルに同じテキストが含まれているかどうかを確認するにはどうすればいいですか

2つの異なるファイルに同じテキストが含まれているかどうかを確認するにはどうすればいいですか

2 つのファイルにテキスト文字列が存在するかどうかを確認 (トリックまたはショートカットを使用) したいです。

ファイル1の内容は

a.txt
b.txt
c.txt
d.txt

ファイル2の内容は

c.txt
a.txt
d.txt

ファイル 1 の文字列がファイル 2 に一致する文字列があるかどうかをどのように確認すればよいでしょうか?

答え1

指示

方法1:

for i in `cat p1`; do grep -i "$i" p2 >/dev/null; if [[ $? == 0 ]]; then echo "$i exsists in both files"; else echo "$i doesnt exsists in file p2"; fi; done

出力

a.txt exsists in both files
b.txt doesnt exsists in file p2
c.txt exsists in both files
d.txt exsists in both files

答え2

join、およびsortgrep

join <(sort /path/to/source) <(sort /path/to/destination) | grep '<string to check>

テスト

cat source
a.txt
b.txt
c.txt
d.txt

cat destination
c.txt
a.txt
d.txt

join <(sort source) <(sort destination) | grep 'a.txt'
a.txt

join <(sort source) <(sort destination) | grep 'b.txt'

2つのファイルの内容が一致していないかどうかを確認する必要がある場合は、次のコマンドを発行します。

cmp --silent <(sort source) <(sort destination) || echo "files are different"

テスト

cmp --silent <(sort source) <(sort destination) || echo "files are different"
files are different

/var/tmp/unmatchedファイル内の宛先ファイルに含まれていないソースファイルのすべての行を追加するには

comm -23 <(sort source) <(sort destination) > /var/tmp/unmatched

宛先ファイルに含まれていないすべての行をソースファイルから削除する

comm -1 <(sort source) <(sort destination) >| source

ここでは bash を使用しており、noclobber を に設定している場合はset -o noclobber、構文 を使用する必要があります>|

答え3

以下のawkコマンドを使用して実行します

f2count=`awk 'END{print NR}' p2`
f1count=`awk 'END{print NR}' p1 `
comm_p1_p2=`awk 'NR==FNR{a[$0];next}($0 in a){print $0}' p1 p2| awk 'END{print NR}'`

if [[ $f1count -eq $f2count ]] && [[ $f1count -eq $comm_p1_p2 ]]; then echo "both files p1  and p2 content are same"; else echo "different content found on file p1  and p2"; fi

関連情報