LoginSignup
9
10

More than 5 years have passed since last update.

Perlの正規表現でgrepしたい

Posted at

pcregrepで複数行の文字列をマッチさせる - Qiita
http://qiita.com/biatunky/items/30bd07d7c9384d0c7895
に触発されて。

Perl病でもPerl正規表現grepがしたい

Perlの正規表現に慣れると、grepの正規表現では満足できない身体になってしまいます。

$ cat a.txt
123
aaa
345
bbb
a5a
$ cat a.txt  | grep -e '\d+'
(何も出力されない)

Perlワンライナーを使う

ワンライナーに投げてしまう方法です。
デメリットはperl実行処理コストぐらい?

$ cat a.txt  | perl -nlE 'say if /\d+/'
123
345
a5a

こんな置換も簡単

$ cat a.txt | perl -nlE 'say if s/(\d+)/[$1]/g'
[123]
[345]
a[5]a
オプション 意味
-n whileループにする "while (<>) { }"
-l 改行を取り除く(chomp)、print関数の場合は'\n'をつける
-E sayを使えるように

grepの-Pオプションを使う

grepにも実はPerl正規表現拡張を使うオプションがあります。(未確認、PCRE?)
デメリットはmanページにあるように実験的なので将来的に削除される可能性があります。

  -P, --perl-regexp
          Interpret  PATTERN as a Perl regular expression.  This is highly
          experimental and grep -P may warn of unimplemented features.
$ cat a.txt  | grep -P '\d+'
123
345
a5a
9
10
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
9
10