2つのファイルを比較し、出力をfile1_value、file2_value、Match / NoMatchとして保存します。

2つのファイルを比較し、出力をfile1_value、file2_value、Match / NoMatchとして保存します。

ファイルが2つありますが、

ファイル1->

1
2
2
3
5

ファイル2->

1
3
2
6

file3という3番目のファイルに出力を保存したいです。

1,1,Match
2,2,Match
2,,NoMatch
3,3,Match
5,,NoMatch
 ,6,NoMatch

頑張りました。

sort file1 > file1sorted.txt
sort file2 > file2sorted.txt

# Combine the sorted files with a comma and store it in a new file
paste -d ',' file1sorted.txt file2sorted.txt   > mergedsortedfile.txt

# Compare the columns and store the result in a new file
awk -F',' '{print $1 == $2 ? "MATCH" : "NO MATCH"}' mergedsortedfile.txt > result.txt

# Merge the result file with the already existing merged file
paste -d ', ' mergedsortedfile.txt result.txt > final_result.txt

結果は次のとおりです。

1,1,MATCH
2,2,MATCH
2,3,NO MATCH
3,6,NO MATCH
5,,NO MATCH

ベストアンサー1

commソートされたデータの使用:

$  comm <( sort -n file1 ) <( sort -n file2 )
                1
                2
2
                3
5
        6

この出力はタブで区切られます。列1と2のすべての項目を「NoMatch」と表示し、列3のすべての項目を「Match」と表示できますawk

$ comm  <( sort -n file1 ) <( sort -n file2 ) |
  awk -F$'\t' 'BEGIN { OFS="," } $3 { print $3, $3, "Match"; next } { print $1, $2, "NoMatch" }'
1,1,Match
2,2,Match
2,,NoMatch
3,3,Match
5,,NoMatch
,6,NoMatch

スクリプトawkはタブ区切り入力()を読み取り、-F$'\t'カンマを出力フィールド区切り記号(OFS=",")として使用します。フィールド3に何かがある場合は、Matchフィールド3に2回出力され、次の行に進みます。それ以外の場合は、フィールド1と2、およびinputのNoMatch3番目のフィールドを出力します。

おすすめ記事