使用用于多字符 RS 的 GNU awk:
$ cat tst.awk
BEGIN { RS="^$"; ORS="" }
ARGIND==1 { old = $0 }
ARGIND==2 { new = $0 }
ARGIND==3 {
if ( start = index($0,old) ) {
$0 = substr($0,1,start-1) new substr($0,start+length(old))
}
print
}
$ awk -f tst.awk target.txt replacement.txt configfile.php
foo
'session' =>
array (
'save' => 'redis',
'redis' =>
array (
'host' => '127.0.0.1',
'other_variable' => 'other_setting',
)
)
),
bar
以上是在这些输入文件上运行的:
$ cat target.txt
'session' =>
array (
'save' => 'files',
),
$
$ cat replacement.txt
'session' =>
array (
'save' => 'redis',
'redis' =>
array (
'host' => '127.0.0.1',
'other_variable' => 'other_setting',
)
)
),
$
$ cat configfile.php
foo
'session' =>
array (
'save' => 'files',
),
bar
$
对于其他 awk 来说,它是:
$ cat tst.awk
FNR==1 { ++argind }
argind==1 { old = (FNR>1 ? old RS : "") $0 }
argind==2 { new = (FNR>1 ? new RS : "") $0 }
argind==3 { rec = (FNR>1 ? rec RS : "") $0 }
END {
if ( start = index(rec,old) ) {
rec = substr(rec,1,start-1) new substr(rec,start+length(old))
}
print rec
}
$ awk -f tst.awk target.txt replacement.txt configfile.php
foo
'session' =>
array (
'save' => 'redis',
'redis' =>
array (
'host' => '127.0.0.1',
'other_variable' => 'other_setting',
)
)
),
bar