main.txt
、out.txt
の3つのファイルがあります。 inin.txt
のすべての内容をの内容に変えたいと思います。out.txt
main.txt
in.txt
out.txt
両方にin.txt
複数の行とさまざまな特殊文字を含めることができます。この文字列を正しく読み、エスケープするにはどうすればよいですか?
これは、特殊文字、重複一致、不完全一致、冗長一致など、いくつかの極端なケースの例です。
main.txt
:
foo
Replace these
three lines
with some $.*\'"& in it
bar
Replace these
three lines
with some $.*\'"& in it
Replace these
three lines
with some $.*\'"& in it
three lines
Replace these
three lines
three lines
with some $.*\'"& in it
baz
out.txt
:
Replace these
three lines
with some $.*\'"& in it
in.txt
:
Replacement lines
also with $.*\'"&
予想出力:
foo
Replacement lines
also with $.*\'"&
bar
Replacement lines
also with $.*\'"&
Replacement lines
also with $.*\'"&
three lines
Replace these
three lines
three lines
with some $.*\'"& in it
baz
ベストアンサー1
そしてperl
:
perl -0777 -e '$out = <>; $in = <>; $_ = <>; s/\Q$out\E/$in/g; print
' out.txt in.txt main.txt > new-main.txt
メモリに収まるほど小さい限り、ファイルに含めることができるすべての文字または非文字で動作する必要があります(バイナリファイルでも機能します)。
-0777
入力レコード区切り文字を不可能な値に設定して実行と同じにし、引数として渡されたファイル$/ = undef
から<>
順番にファイル全体を読み取ります。
したがって、//全体の内容が、および、$out
それぞれあります。$in
$_
out.txt
in.txt
main.txt
$_
s/pattern/replacement/flags
print
基本的に演算子によって処理される変数です。パターン空間存在するsed
。
ここでのパターンは、内部コンテンツが正規表現ではなく文字通りに処理されるようにすることです\Q$out\E
。\Q...\E
このg
フラグは、のように発生するすべての状況を置き換えますsed
。
または、コマンド出力(たとえばls|
、<<>>
ファイルパスとしてのみ解釈されるコマンド出力)を代わりに使用します。