I ♥ WordPress

[時間割:Perl]『ミニマルPerl』その7
2008/10/31 02:40 posted by kunkichi

今日も外で勉強してきました。やっぱり外はいいですね。ということで木曜日は『Perl』です。今回からsedをPerlで置き換えてみようというところです。

ミニマルPerl Unix/LinuxユーザのためのPerl習得法
Tim Maher
オライリージャパン
売り上げランキング: 96883
  • おなじみの置換。sedとほとんど同じ。$ echo "abcde" | perl -wpl -e 's/abc/ABC/g;'
    ABCde
  • 複数の置換を一気に。まずはsed。これは知らなかった。$ cat example.sed
    s/a/A/g
    s/b/B/g
    s/c/C/g
    $ echo "abcde" |  sed -f example.sed
    ABCde
    これをPerlで。コマンドラインだとこんな感じ。$ echo "abcde" | perl -wpl -e '
    > s/a/A/g;
    > s/b/B/g;
    > s/c/C/g;'
    ABCde
    スクリプトだと以下。$ cat example.pl
    #!/usr/bin/perl -wpl
    s/a/A/g;
    s/b/B/g;
    s/c/C/g;
    $ echo "abcde" | ./example.pl
    ABCde
  • 行を指定して置換。sedの場合。$ cat sample.txt
    This is sentence 1.
    This is sentence 2.
    This is sentence 3.
    $ sed '1s/sentence/REVISED_SENTENCE/g;' sample.txt
    This is REVISED_SENTENCE 1.
    This is sentence 2.
    This is sentence 3.
    Perlだと行番号を表す$.を使う。$ perl -wpl -e '$. == 1 and s/sentence/REVISED_SENTENCE/g;' sample.txt
    This is REVISED_SENTENCE 1.
    This is sentence 2.
    This is sentence 3.
  • -0digitを使って、段落単位、ファイル単位もできる。$ cat sample2.txt
    This is paragraph 1.
    And, this is a sentence for paragraph 1.
     
    This is paragraph 2.
    And, this is a sentence for paragraph 2.
     
    This is paragraph 3.
    And, this is a sentence for paragraph 3.
    $ perl -00 -wpl -e '$. == 1 and s/paragraph/PARAGRAPH/g;' sample2.txt
    This is PARAGRAPH 1.
    And, this is a sentence for PARAGRAPH 1.
     
    This is paragraph 2.
    And, this is a sentence for paragraph 2.
     
    This is paragraph 3.
    And, this is a sentence for paragraph 3.
     
  • 後方参照。sedとPerlだとマッチ部分のカッコのエスケープが逆なので注意。まずsed。$ echo "This is a sample sentence." | sed 's/^\(.*\) \(sentence\.\)$/\1 REVISED \2/g'
    This is a sample REVISED sentence.
    sedはカッコにエスケープをつけると正規表現の部分マッチ用のカッコとなる。次にPerl。$ echo "This is a sample sentence." | perl -wpl -e 's/^(.*) (sentence\.)$/$1 REVISED $2/g'
    This is a sample REVISED sentence.
    Perlの場合は逆にエスケープをつけない場合が正規表現のマッチ用カッコとなる。
  • 行番号で表示を指定。例として2行目以降を出力してみる。$ sed -n '2,$p' sample.txt
    This is sentence 2.
    This is sentence 3.
    Perlだとこんな感じ。$ perl -wnl -e '$. > 1 and print;' sample.txt
    This is sentence 2.
    This is sentence 3.
  • もちろん、さっきとおんなじように、-0digitを使えば、段落単位・ファイル単位とかも可能

sedで後方参照する時っていつもカッコのエスケープ忘れてハマるんだよね、苦笑。行番号の箇所なんかもキー入力はPerlのほうが少し多くなるけど、直感的。

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

トラックバックURL





このページの先頭へ