
両方のファイルにテキスト文字列があることを確認したい(トリックまたはショートカット)。
ファイル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'
両方のファイルの内容が一致しないことを確認する必要がある場合は、次のコマンドを実行できます。
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