[時間割:Perl]『ミニマルPerl』その5
2008/10/15 02:05 posted by kunkichi
さて、祝日分のアップをします。まずは『Perl』から。
ミニマルPerl Unix/LinuxユーザのためのPerl習得法
posted with amazlet at 08.10.06
Tim Maher
オライリージャパン
売り上げランキング: 96883
オライリージャパン
売り上げランキング: 96883
- 正規表現でこれまでは、デリミタに¥s+、数値に[0-9]とかでベタに指定してたけど、これからは¥bとか¥dとか使おう。
- fgrepみたいな、メタキャラクタをそのままリテラルで使う場合は、¥Q…¥E。
- マッチした部分を取り出す場合は、$&を使う。
$ echo "12345 123 abced abc" | perl -wnl -e '/\b\d\d\d\d\d\b/ and print $&;'
12345 - マッチしない場合(grep -v)は、orを使う。
$ echo "12345
> 123
> abcde
> abc" | perl -wnl -e '/\b\d\d\d\d\d\b/ or print;'
123
abcde
abc
- 合致するファイル名だけを出力する(grep -l)の場合は、$ARGVでファイル名を取得。
perl -wnl -e '/\b\d\d\d\d\d\b/ and print $ARGV and close ARGV;' aaa bbb ccc最後にcloseしているのは、合致する文字列が複数業あった場合にファイル名が2重に出力されるのを防ぐために、合致した時点でcloseして終わるため。
aaa
ちなみに、closeしないとこうなる。$ perl -wnl -e '/\b\d\d\d\d\d\b/ and print $ARGV;' aaa bbb ccc
aaa
aaa - 大文字小文字を無視する(grep -i)の場合は、マッチ修飾子iを使う。
$ echo "aaa
> AAA
> bbb
> BBB" | perl -wnl -e '/aaa/i and print;'
aaa
AAA - egrep的だったり、パイプを使った段階的フィルタ、みたいなのはperlだと簡単。
perl -wnl -e '/aaa/ andパイプで書くと
/bbb/ and
/ccc/ and
/ddd/ and
print;' sample.txtgrep "aaa" sample.txt | grep "bbb" | grep "ccc" | grep "ddd"メモリ消費やポータビリティの点でPerlのほうがらくちん。 - 行単位じゃなくて、複数行でのマッチングも簡単。まずは段落。以下のようなldifファイルがあるとして、
$ cat sample.ldifuidがtest2のレコードを抽出。
dn: uid=test1,ou=people,dc=example,dc=com
uid: test1
objectclass: posixAccount
objectclass: account
userPassword:password1
loginshell: /bin/bash
uidNumber: 201
gidNumber: 201
homeDirectory: /home/test2
gecos: test1
description: "Test User 1"
・・・
dn: uid=test3,ou=people,dc=example,dc=com
uid: test3
objectclass: posixAccount
objectclass: account
userPassword:password3
loginshell: /bin/bash
uidNumber: 203
gidNumber: 203
homeDirectory: /home/test3
gecos: test3
description: "Test User 3"$ perl -00 -wnl -e '/uid: test2/ and print;' sample.ldif
dn: uid=test2,ou=people,dc=example,dc=com
uid: test2
objectclass: posixAccount
objectclass: account
userPassword:password2
loginshell: /bin/bash
uidNumber: 202
gidNumber: 202
homeDirectory: /home/test2
gecos: test2
description: "Test User 2" - 今度はさっきのレコードがそれぞれ独立したldifファイルだった場合。この場合はファイルモードを使う。
$ perl -0777 -wnl -e '/uid: test2/ and print;' test1.ldif test2.ldif test3.ldif結果は上と同じ。
ここまでは今までにも出てきてるので問題ないね。段落モードとか実際に使えそうなシチュエーションを想定してやってみました。
さて、次回は、「行をまたがる正規表現」からです。これは結構必要となるシチュエーションが多いので重要ですね。






コメント&トラックバック
トラックバックURL: