sed用于简单替换个别行,即。对于其他任何事情,你都应该使用awk来提高清晰度,健壮性,效率等等。请参阅Is it possible to escape regex metacharacters reliably with sed了解一些你必须跳过的环节,甚至开始考虑想出一个强大的sed脚本来完成这项工作。
简单,可靠的方法做你想做的(在这种情况下使用GNU AWK多焦RS):
$ cat tst.awk
BEGIN { RS="^$"; ORS="" }
ARGIND==1 { old=$0; next }
ARGIND==2 { new=$0; next }
s=index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+length(old)) }
{ print }
$ cat old
"scripts": [
"../node_modules/something.js"
],
$ cat new
"scripts": [
"../node_modules/something1.js",
"../node_modules/something2.js"
],
$ cat file
foo
"scripts": [
"../node_modules/something.js"
],
bar
$ awk -f tst.awk old new file
foo
"scripts": [
"../node_modules/something1.js",
"../node_modules/something2.js"
],
bar
你尝试过什么?我猜你不希望我们为你写出整个剧本。 ;) – Markus
我只需要知道这是否可以完成。我不是要求scipt只是从文件中替换指定文本的方式(如果可以的话) – unzip700