両方のファイル(1つの列を含む)からデータを読み取り、該当する場合はデータを表示します。

両方のファイル(1つの列を含む)からデータを読み取り、該当する場合はデータを表示します。

両方のファイルのデータを比較しようとしています。そのうちの1つには列が含まれており、両方のファイルにあるデータを印刷したいと思います。

ファイル1:

item1
item2
item3

ファイル2:

itemA item1
itemB item2
itemC item3

そのため、ファイル1の列2をファイル2と比較し、同じ場合は行全体を表示したいと思います。

例えばファイル1含む:

data1
data2

そしてファイル2含む:

dataA data1
dataC data3

以下のみ表示されます。

dataA data1

これは、file1 のデータ項目を含む file2 の行であるためです。

事前にありがとう

ベストアンサー1

使用grep:

grep -Fwf file1 file2

~からman grep:

-F, --fixed-strings
    Interpret PATTERN as a list  of  fixed  strings  (instead  of  regular  expressions),  separated  by
    newlines, any of which is to be matched.

-f FILE, --file=FILE
    Obtain patterns from FILE, one per line.  If this option is used multiple times or is combined  with
    the -e (--regexp) option, search for all patterns given.  The empty file contains zero patterns, and
    therefore matches nothing.

-w, --word-regexp
    Select only those lines containing matches that form whole words.  The test  is  that  the  matching
    substring  must  either  be  at  the  beginning  of  the line, or preceded by a non-word constituent
    character.  Similarly, it must be either  at  the  end  of  the  line  or  followed  by  a  non-word
    constituent character.  Word-constituent characters are letters, digits, and the underscore.

またはawk:

awk 'NR==FNR{seen[$0]++} ($2 in seen)' file1 file2

上で最初に私たちが読んでいるのはファイル1列 1 全体を名前付き配列に保存します。ボン、file2の2番目の列を見て、file1に格納されている列1と一致すると、file2の行全体を印刷します。

join両方のファイルがソートされている場合は、次のコマンドを使用することもできます(そうでない場合は、sortingを介してソートされた出力を渡すことができます)。

join -1 1 -2 2 file1 file2

~からman join

-1 FIELD
      join on this FIELD of file 1

-2 FIELD
      join on this FIELD of file 2

ファイルがソートされていない場合:

join -1 1 -2 2 <(sort file1) <(sort file2)

おすすめ記事