LoginSignup
4
0

More than 3 years have passed since last update.

grepの結果がウザい

Last updated at Posted at 2019-09-25

※ オレオレgrepコマンドを作り直しました。 https://qiita.com/digitarhythm/items/20472caee63344ba4e44

grepの結果がウザい

例えば、grepで、

$ grep localhost /etc/*

とやると、

grep: /etc/python2.7: ディレクトリです
grep: /etc/python3: ディレクトリです
grep: /etc/python3.5: ディレクトリです
grep: /etc/rc0.d: ディレクトリです
grep: /etc/rc1.d: ディレクトリです
grep: /etc/rc2.d: ディレクトリです
grep: /etc/rc3.d: ディレクトリです
grep: /etc/rc4.d: ディレクトリです
grep: /etc/rc5.d: ディレクトリです
grep: /etc/rc6.d: ディレクトリです
grep: /etc/rcS.d: ディレクトリです
grep: /etc/resolvconf: ディレクトリです
grep: /etc/rsyslog.d: ディレクトリです
grep: /etc/samba: ディレクトリです
grep: /etc/sane.d: ディレクトリです
grep: /etc/security: ディレクトリです
grep: /etc/selinux: ディレクトリです
grep: /etc/sensors.d: ディレクトリです
grep: /etc/sgml: ディレクトリです
grep: /etc/shadow: 許可がありません
grep: /etc/shadow-: 許可がありません
grep: /etc/skel: ディレクトリです
・
・
・

みたいに出てウザい。
なので、grepの「-s」オプションを使うとエラー表示が抑制される。

$ grep -s localhost /etc/*
/etc/hosts:127.0.0.1    localhost
/etc/hosts:::1          localhost ip6-localhost ip6-loopback

しかし、カレントディレクトリの全ファイルを対象とする場合とかだと、最後のパラメータを指定するのが面倒くさい。
なので「grp」という名前で、

#!/usr/bin/env bash
if [ -z "${1}" ]; then
  echo "parameter required."
  echo "usage:"
  echo "grp [-r] search_string [search_direcotry]"
  exit
fi

if [ ${1} = "-r" ]; then
  if [ -z ${3} ]; then
    eval '/usr/bin/env grep -sr ${2} *'
  else
    eval '/usr/bin/env grep -sr ${2} ${3}'
  fi
else
  if [ -z ${2} ]; then
    eval '/usr/bin/env grep -s ${1} *'
  else
    eval '/usr/bin/env grep -s ${1} ${2}/*'
  fi
fi

というスクリプトを書いた。

$ grp hoge

とやると、カレントディレクトリ内の全ファイルを対象に「hoge」を検索する。
ヒットした行だけ表示される。

$ grp -r hoge

とやるとディレクトリ階層を掘り下げてgrepする(rgrepと同じ動作)。

最後の引数としてディレクトリを指定すると、そのディレクトリ内の全ファイルを対象に実行される。
ファイルを指定すると実行されないので注意。

4
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
4
0