0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【備忘録】`grep`コマンドでファイルパスを表示する/しない

0
Last updated at Posted at 2024-06-10

環境

  • Ubuntu 22.04.4 LTS
  • grep 3.7

はじめに

grepコマンドでファイルパスを表示する/しないオプションを探すのに手間取ったので、備忘録としてファイルパスがどのようなときに表示されるか表示されないかを記載します。

前提

targetディレクトリの中にbar.txtfoo.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.
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?