参照リンク:ファイルの特定の文字列の後にテキストを挿入するには? 次の入力ファイルがあります。
Some text
Random
[option]
Some stuff
「[オプション]」の前に1行のテキストを追加したいです。
Some text
Random
Hello World
[option]
Some stuff
このコマンドは次のとおりです。
sed '/\[option\]/i Hello World' input
動作します
が、次のコマンドは次のとおりです。
perl -pe '/\[option\]/i Hello World' input
動作しません。
同等のperlコマンドは何ですか?
修正する:
@terdonと@Sundeepのおかげで、次の部分的な解決策を見つけました。
perl -lpe 'print "Hello World" if /^\[option\]$/' input
しかし、毎回挿入するのではなく、「[オプション]」に初めて触れるときにのみテキスト文字列を挿入したいと思います。
たとえば、
Some text
Random
[option]
Some stuff
test1
[option]
test2
次のようになります。
Some text
Random
Hello World
[option]
Some stuff
test1
Hello World
[option]
test2
いいえ:
Some text
Random
Hello World
[option]
Some stuff
test1
[option]
test2
私が望むように。
ベストアンサー1
Perlのアプローチは次のとおりです。
$ perl -ne 'if(/\[option\]/){print "*inserted text*\n"}; print' input
Some text
Random
*inserted text*
[option]
Some stuff
より簡潔な別の内容は次のとおりです。
$ perl -ne '/\[option\]/?print "*inserted text*\n$_":print' input
Some text
Random
*inserted text*
[option]
Some stuff
これを行うには、ファイル全体をメモリに読み込む必要があります。
$ perl -0777 -pe 's/\[option\]/*inserted text*\n$&/' input
Some text
Random
*inserted text*
[option]
Some stuff