環境
- Ubuntu 22.04.4 LTS
- grep 3.7
はじめに
grepコマンドでファイルパスを表示する/しないオプションを探すのに手間取ったので、備忘録としてファイルパスがどのようなときに表示されるか表示されないかを記載します。
前提
targetディレクトリの中にbar.txtとfoo.txtがあります。
$ tree target
target
├── bar.txt
└── foo.txt
0 directories, 2 files
target/bar.txt
alice
bob
chris
target/foo.txt
dave
eve
alice
動作確認
ファイル名を表示する/しないオプションを使わない
1個のファイルを指定
$ grep -e "lic" target/bar.txt
alice
ファイルパスは表示されない。
複数のファイルを指定
$ grep -e "lic" target/bar.txt target/foo.txt
target/bar.txt:alice
target/foo.txt:alice
ファイルパスは表示される。
ディレクトリを指定
$ grep --recursive -e "lic" target/
target/bar.txt:alice
target/foo.txt:alice
ファイルパスは表示される。
ファイルパスを表示する/しないオプションを使う
常にファイルパスを表示する
$ grep --with-filename -e "lic" target/bar.txt
target/bar.txt:alice
-H, --with-filename
Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension.
常にファイルパスを表示しない
$ grep --no-filename -e "lic" target/bar.txt target/foo.txt
alice
alice
-h, --no-filename
Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search.
ファイルパスのみを表示する
マッチするファイルを表示する
$ grep --files-with-match --recursive -e "bob" target
target/bar.txt
-l, --files-with-matches
Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match.
マッチしないファイルを表示する
$ grep --files-without-match --recursive -e "bob" target
target/foo.txt
-L, --files-without-match
Suppress normal output; instead print the name of each input file from which no output would normally have been printed.