2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Perl ワンライナーで複数行置換

Last updated at Posted at 2016-08-31

Perlのワンライナーで複数行置換しようと思って少し苦労したので自分用メモ。
PerlはPerl5です。

複数行置換するためのワンライナー

まず基本形はこの書き方。

$ cat filename | perl -0pe "s/aaa[\r\n ]+bbb/ccc\nddd/gm"

これで、aaa改行bbbがccc改行dddに置換されます。

ネットやQiitaで色々試しましたが、これ以外はうまくできなかった……
改行コード回りが微妙な感じでした。

エスケープのまとめ

エスケープは細かいところ覚えられないので、メモっておきます。

最初ワンライナーのところをシングルクォートでやっていたのですけど、途中でダブルクォートにしてやりなおし。というのも、置換する対象がシングルクォート含むことが多いのでそうしておきました。

Perlワンライナーのダブルクォート内に書く正規表現のエスケープはこんなルール。

( ⇒ \(
) ⇒ \)
/ ⇒ \/
. ⇒ \.
" ⇒ \"
$ ⇒ \x24

元の文字列を、以上のルールでエディタで一括置換して使っています。
例えばこうなります。

$.ajax({url:'http://localhost/',type:"GET"});
↓エスケープする
\x24\.ajax\({url:'http:\/\/localhost\/',type:\"GET\"}\);
↓正規表現にいれる
"s/aaa/\x24\.ajax\({url:'http:\/\/localhost\/',type:\"GET\"}\);/gm"

2
2
1

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?