替换文件中双引号中的第三个单词

yae*_*ael 1 rhel sed perl json

这是json我们要编辑的文件

示例 1

{
  "topics": [{"topic": "hfgt_kejd_tdsfd”}],
  "version": 1
}
Run Code Online (Sandbox Code Playgroud)

示例 2

{
  "topics": [{"topic": "hfgt_kj_fsrfdfd”}],
  "version": 1
}
Run Code Online (Sandbox Code Playgroud)

我们想topics用其他词(通过 sed 或 perl one liner )替换该行中的第三个词

关于向例子1,预期结果,当我们想要替换hfgt_kejd_tdsfdtest_1

{
  "topics": [{"topic": "test_1”}],
  "version": 1
}
Run Code Online (Sandbox Code Playgroud)

例3

more /tmp/file.json

{
  "topics": [{"topic": "TOPIC_GGGG”}],
  "version": 1
}


# sed  's/\(topic\": "\)[a-z_]*/\1test_1/'  /tmp/file.json

{
  "topics": [{"topic": "test_1TOPIC_GGGG”}],
  "version": 1
}
Run Code Online (Sandbox Code Playgroud)

Kus*_*nda 8

使用jq

$ jq '.topics[0].topic |= "test_1"' file.json
{
  "topics": [
    {
      "topic": "test_1"
    }
  ],
  "version": 1
}
Run Code Online (Sandbox Code Playgroud)

这将读取 JSON 文档并将topic数组第一个元素的条目值修改topics为 string test_1

如果您在变量中有您的值(以 UTF-8 编码):

$ val='Some value with "double quotes"'
$ jq --arg string "$val"  '.topics[0].topic |= $string' file.json
{
  "topics": [
    {
      "topic": "Some value with \"double quotes\""
    }
  ],
  "version": 1
}
Run Code Online (Sandbox Code Playgroud)

使用 Perl:

$ perl -MJSON -0777 -e '$h=decode_json(<>); $h->{topics}[0]{topic}="test_1"; print encode_json($h), "\n"' file.json
{"topics":[{"topic":"test_1"}],"version":1}
Run Code Online (Sandbox Code Playgroud)

使用变量:

$ val='Some value with "double quotes"'
$ STRING=$val perl -MJSON -0777 -e '$string = $ENV{STRING}; utf8::decode $string; $h=decode_json(<>); $h->{topics}[0]{topic}=$string; print encode_json($h), "\n"' file.json
{"topics":[{"topic":"Some value with \"double quotes\""}],"version":1}
Run Code Online (Sandbox Code Playgroud)

这两者都是使用PerlJSON模块解码JSON文档,改变需要改变的值,然后输出重新编码后的数据结构。错误处理留作练习。

对于第二段代码,要插入的值作为环境变量传递STRING到 Perl 代码中。这是由于使用 .slurp 模式从文件中读取 JSON 文档-0777