![2つの異なるファイルに同じテキストが含まれているかどうかを確認するにはどうすればいいですか](https://rvso.com/image/169430/2%E3%81%A4%E3%81%AE%E7%95%B0%E3%81%AA%E3%82%8B%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%AB%E5%90%8C%E3%81%98%E3%83%86%E3%82%AD%E3%82%B9%E3%83%88%E3%81%8C%E5%90%AB%E3%81%BE%E3%82%8C%E3%81%A6%E3%81%84%E3%82%8B%E3%81%8B%E3%81%A9%E3%81%86%E3%81%8B%E3%82%92%E7%A2%BA%E8%AA%8D%E3%81%99%E3%82%8B%E3%81%AB%E3%81%AF%E3%81%A9%E3%81%86%E3%81%99%E3%82%8C%E3%81%B0%E3%81%84%E3%81%84%E3%81%A7%E3%81%99%E3%81%8B.png)
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
、およびsort
grep
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