这很难用 sed 稳健地完成,您应该使用适当的 JSON 库。
但是要使用 GNU sed 做你想做的事情,你可以做这样的事情(这里不检查结尾的逗号):
sed '/require/,/},/ s/},/, "friendsofsymfony\/user-bundle": "\*"\n&/
要检查结尾逗号,您需要进行更多解析:
解析.sed
/^[ \t]*"require/ { # when 'require' found
: a
N # run through pairwise
/\n[\t ]*\},/! { P; s/[^\n]+\n//; ba } # lines until '},' is found
/,\n/! s/\n/,&/ # append comma if not present
s/\n([\t ]*)},/\n\1\1"friendsofsymfony\/user-bundle": "\*"&/
}
运行:
sed -rf parse.sed infile
在提供的示例文件上运行时parse.sed的输出摘录:
[...]
"require": {
"php": ">=5.3.3",
"symfony/symfony": "2.2.*",
"doctrine/orm": ">=2.2.3,<2.4-dev",
"doctrine/doctrine-bundle": "1.0.*",
"twig/extensions": "1.0.*",
"symfony/assetic-bundle": "2.1.*",
"symfony/swiftmailer-bundle": "2.1.*",
"symfony/monolog-bundle": "2.1.*",
"sensio/distribution-bundle": "2.2.*",
"sensio/framework-extra-bundle": "2.2.*",
"sensio/generator-bundle": "2.2.*",
"jms/security-extra-bundle": "1.3.*",
"jms/di-extra-bundle": "1.2.*",
"friendsofsymfony/user-bundle": "*"
},
[...]