LoginSignup
63
44

More than 5 years have passed since last update.

2つのファイルの共通行を抽出する方法

Posted at

はじめに

2つのリストから共通した行を抽出する方法

grepコマンドを使う方法

文字の大小・ソートしていないファイルに対してイッパツで対応出来ます。

コマンド

grep -x -i -f  file1 file2

説明

  • オプションx

    行全体を検索対象にする

  • オプションi

    検索条件に大文字と小文字の区別をなくす

  • オプションf

     検索パターンとしてfileの内容を使用する

実行例

$ cat test1.txt
eee12345
AAA12345
$ cat test2.txt
aaa12345
bbb12345
ccc12345
ddd12345
eee12345
$
$ grep -x -i -f  test1.txt test2.txt
aaa12345
eee12345

commコマンドを使う方法

なじみのないcommコマンドを使う方法。
commコマンドのオプション1とオプション2をあわせて使うと確かに共通行が出る!!
※inputファイルはソート済みであること。
※文字の大小もそろえてあること。

コマンド

comm -1 -2 file1 file2

説明

  • オプション1

     FILE1で指定したファイルの内容のみに存在する行を出力しない。

  • オプション2

     FILE2で指定したファイルの内容のみに存在する行を出力しない。

実行例

  • ソート済み・大小もそろえたファイルを対象とした場合
$ cat test1.txt
aaa12345
eee12345
$ cat test2.txt
aaa12345
bbb12345
ccc12345
ddd12345
eee12345
$ comm -1 -2 test1.txt test2.txt
aaa12345
eee12345
  • ソートを行わないファイルを対象としたとき
$ cat test1.txt
eee12345
AAA12345
bbb12345
[vagrant@localhost tmp]$ comm -1 -2 test1.txt test2.txt
eee12345
comm: file 1 is not in sorted order

参考にしたサイト

63
44
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
63
44