1
1

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でよく使うコマンドのメモ書き

Last updated at Posted at 2021-05-27

grepでよく使うコマンドのメモ書きです。

カレントディレクトリ配下の全てのファイルからhogehogeを検索する
$ grep -ir hogehoge .

-rオプションはサブディレクトリ内のファイルも再帰的に検索する
-iオプションは大文字小文字を区別して検索する

検索ヒットした対象の行だけじゃなくて上下の行も同時に表示する

例えば、対象行と上下4行を表示する

$ grep -ir4 hogehoge .
特定のディレクトリを検索対象から除外したい場合、--exclude-dirオプションを使う
$ grep -r hogehoge . --exclude-dir=./test

複数のディレクトリを除外したい場合は(./testと./test2を除外)、

$ grep -r hogehoge . --exclude-dir={./test,./test2}
metaタグの行でdescriptionについて書いている部分を検索する
$ grep -ir meta.*desc .

 「.*」の部分は、.は何かの文字(空白も含む)、*は直前の文字の0回以上の繰り返し

grep,sedでカレントディレクトリ以下の全てのファイルを対象に、文字列を置換する

カレントディレクトリ以下の全てのファイルを対象に、文字列「ほげほげ:」を「もげもげもげ:」に置換するコマンドです。

grep -rl 'ほげほげ:' . | xargs sed -i 's/ほげほげ:/もげもげもげ:/g'
->sed: 1: "./dir1/dir2 ...": invalid command code .

ただ、自分のmacOSのコマンドライン環境だと、上の通りinvalid command codeエラーが発生しました。GNUのsedなら上のコマンドでできるみたいです。
macOSのsedの場合、sedの引数に''を追加する。

grep -rl 'ほげほげ:' . | xargs sed -i '' 's/ほげほげ:/もげもげもげ:/g'

参考サイト
macOS High Sierraでsedで上書き更新しようとして-iオプションを付けて実行したらsed: 1: "ファイルパス": invalid command code mとなったときの対応方法

\eをgrep検索する
$ bind -p | grep '\\e'
-H(Hオプション)をgrep検索する
$ grep -r '\-H' .
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?