我必须按以下方式用相同的单词+下划线+数字替换冒号后的每个字符串:
{"first": "1_first", "second": "1_second"}
预期成绩:
{"first": "first_1", "second": "second_1"}
{"first": "first_20", "second": "second_20"}
{"first": "first_33", "second": "second_33"}
我已经成功完成第一个:
echo '{"first": "first_1", "second": "second_1"}' | sed "s/\( \".*\",\)/ \"first_$j\",/"
结果是:
{"first": "first_888", "second": "second_1"}
但第二个就有问题了。我认为这个表达式太贪婪了:
echo '{"first": "first_1", "second": "second_1"}'|sed "s/\( \".*\)\"}/ \"second_$j\"}/"
这一句删减太多了:
{"first": "second_888"}
也许有一些更优雅的方法来做到这一点?用 1 个表达式而不是 2 个?
答案1
我不确定这是否是您想要的,用键中的字符串替换值。只要键或值中没有(转义)引号,就可以工作。如果您这样做,或者甚至可能,最好使用真正的解析器。
$ num=42
$ echo '{"foo": "xxx", "bar": "yyy"}' | \
sed -E 's/"([^"]*)": "[^"]*"/"\1": "\1_'$num'"/g'
{"foo": "foo_42", "bar": "bar_42"}
答案2
使用jq
:
$ cat data.json
{"first": "xxx", "second": "xxx"}
{"first": "yyy", "second": "yyy"}
{"first": "zzz", "second": "zzz"}
$ jq 'with_entries(.value = .key + "_42")' data.json
{
"first": "first_42",
"second": "second_42"
}
{
"first": "first_42",
"second": "second_42"
}
{
"first": "first_42",
"second": "second_42"
}
使用 shell 变量:
$ number=9
$ jq 'with_entries(.value = .key + "_'$number'")' data.json
{
"first": "first_9",
"second": "second_9"
}
{
"first": "first_9",
"second": "second_9"
}
{
"first": "first_9",
"second": "second_9"
}
如果您喜欢紧凑的输出:
$ jq -c 'with_entries(.value = .key + "_'$number'")' data.json
{"first":"first_9","second":"second_9"}
{"first":"first_9","second":"second_9"}
{"first":"first_9","second":"second_9"}