Linux:grepコマンドでファイル名のみを出力する方法

スポンサーリンク

grepコマンドでファイル名のみを出力する方法

grepコマンドでファイル名のみを出力するには-lオプションを指定します。

 

オプションの説明

  -L, --files-without-match print only names of FILEs containing no match
  -l, --files-with-matches  print only names of FILEs containing matches

 

以下のファイルを対象とします。

$ cat test1.txt
apple
$ cat test2.txt
banana
$ cat test3.txt
orange

 

-lオプションを指定した場合

$ grep -l 'banana' test*.txt
test2.txt

 

-lオプションを指定しない場合

$ grep 'banana' test*.txt
test2.txt:banana

 

なお、マッチ(一致)しないファイル名のみを出力したい場合は-Lオプションを指定します。

$ grep -L 'banana' test*.txt
test1.txt
test3.txt