grepコマンドでサブディレクトリー配下も検索

スポンサーリンク

grepコマンドのオプションでサブディレクトリー配下を検索します。

検証した環境

$ cat /etc/os-release
PRETTY_NAME="Debian GNU/Linux 11 (bullseye)"
NAME="Debian GNU/Linux"
VERSION_ID="11"
VERSION="11 (bullseye)"
VERSION_CODENAME=bullseye
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"
$ uname -r
5.15.56-v8+
$ grep --version
grep (GNU grep) 3.6
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Mike Haertel and others; see
<https://git.sv.gnu.org/cgit/grep.git/tree/AUTHORS>.

grepコマンドの再帰的実行

$ tree ・・・ data[1-2].{txt,dat}ファイルが存在しているとする
.
└─ txt1
    ├─ data1.dat
    ├─ data1.txt
    └─ txt2
        ├─ data2.dat
        └─ data2.txt

2 directories, 4 files
$ grep -r orangetakam ./ ・・・ 「orangetakam」文字列をカレンとディレクトリーから配下を検索
./txt1/txt2/data2.txt:orangetakam
./txt1/txt2/data2.dat:orangetakam
./txt1/data1.txt:orangetakam
./txt1/data1.dat:orangetakam
$ grep -lr orangetakam ./ ・・・ ファイル名だけ出力したい場合
./txt1/txt2/data2.txt
./txt1/txt2/data2.dat
./txt1/data1.txt
./txt1/data1.dat
$ grep -lr orangetakam --include='*.txt' ./ ・・・ 「*.txt」のファイルを検索対象
./txt1/txt2/data2.txt
./txt1/data1.txt
$ grep -lr orangetakam --exclude='*.txt' ./ ・・・ 「*.txt」のファイルを検索除外
./txt1/txt2/data2.dat
./txt1/data1.dat