如何使用正则表达式替换子字符串值?

时间:2016-04-15 06:51:41

标签: regex linux sed

例如,我在一个文件中有几行,每行都是一个字符串,如下所示:

{"a":"53124647,44398061,44398058","b":"hello","c":"ha"}
{"b":"99","a":"44398049,44398031,44398028,10007072315,9569405558,10007072318","c":"ha"}
...

如果每一行被视为json对象,则每行中键"a"的值的长度是灵活的,因此如何使用sedregular expression来替换这一对密钥"a"及其值"a":"10"

2 个答案:

答案 0 :(得分:2)

$ echo '{"a":"53124647,44398061,44398058","b":"hello","c":"ha"}
{"b":"99","a":"44398049,44398031,44398028,10007072315,9569405558,10007072318","c":"ha"}' | sed 's/"a":"[^"]*"/"a":"10"/g'
{"a":"10","b":"hello","c":"ha"}
{"b":"99","a":"10","c":"ha"}

答案 1 :(得分:1)

$ echo '{"a":"53124647,44398061,44398058","b":"hello","c":"ha"}' | sed 's@"a":"[^"]*"@"a":"10"@'
{"a":"10","b":"hello","c":"ha"}