bash - jq 直接替换文件上的文本(如 sed -i)

标签 bash jq in-place edit-in-place

我有一个需要在特定条件下更新的 json 文件。

示例 json

{
   "Actions" : [
      {
         "value" : "1",
         "properties" : {
            "name" : "abc",
            "age" : "2",
            "other ": "test1"
          }
      },
      {
         "value" : "2",
         "properties" : {
            "name" : "def",
            "age" : "3",
            "other" : "test2"
          }
      }
   ]
}

我正在写一个脚本,它利用Jq来匹配一个值并更新,如下所示

cat sample.json |  jq '.Actions[] | select (.properties.age == "3") .properties.other = "no-test"'

输出(打印到终端)

{
  "value": "1",
  "properties": {
    "name": "abc",
    "age": "2",
    "other ": "test1"
  }
}
{
  "value": "2",
  "properties": {
    "name": "def",
    "age": "3",
    "other": "no-test"
  }
}

虽然此命令进行了所需的更改,但它会在终端上输出整个 json,并且不会对文件本身进行更改。

请告知是否可以让 jq 直接对文件进行更改(类似于 sed -i)。

最佳答案

这篇文章解决了关于缺少与 sed 的“-i”选项等效的问题,特别是所描述的情况:

I have a bunch of files and writing each one to a separate file wouldn't be easy.

有多种选择,至少如果您在 Mac 或 Linux 或类似环境中工作。它们的优缺点在 http://backreference.org/2011/01/29/in-place-editing-of-files/ 所以我将只关注三种技术:

一个是简单地使用“&&”沿线:

jq ... INPUT > INPUT.tmp && mv INPUT.tmp INPUT

另一个是使用 sponge 实用程序(GNU moreutils 的一部分):

jq ... INPUT | sponge INPUT

第三个选项可能很有用,如果它有利于避免在没有更改的情况下更新文件。这是一个说明这种功能的脚本:

#!/bin/bash

function maybeupdate {
    local f="$1"
    cmp -s "$f" "$f.tmp"
    if [ $? = 0 ] ; then
      /bin/rm $f.tmp
    else
      /bin/mv "$f.tmp" "$f"
    fi
}

for f
do
    jq . "$f" > "$f.tmp"
    maybeupdate "$f"
done

关于bash - jq 直接替换文件上的文本(如 sed -i),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36565295/

相关文章:

node.js - Glob 和 NPM Minimatch : Match all files and directories recursively except for specific directories

linux - 跟踪 ksh 多个 session 的命令历史记录

linux - Bash - 我的脚本错误地重命名了一个文件夹

amazon-web-services - 用于列出所有 api 网关部署的 boto 脚本

json - jq - 如何有条件地过滤掉对象

algorithm - 在线性时间和就地排序

php - linux - 当 php 作为 apache 模块安装时从命令行运行 php 脚本

json - 使用JQ获取所有唯一的JSON key 名称

python - 使用字典替换文本文件中的单词

python - 变量克隆行为不明确