Jq 直接替换文件上的文本(如 sed

编程入门 行业动态 更新时间:2024-10-07 23:21:28
本文介绍了Jq 直接替换文件上的文本(如 sed -i)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I have a json file that needs to be updated on a certain condition.

示例 json

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

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

I am writing a script that makes use of Jq to match a value and update, as shown below

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,并且不会更改文件本身.

While this command makes the needed change, it outputs the entire json on the terminal and does not make change to the file itself.

请告知是否有选项让 jq 直接对文件进行更改(类似于 sed -i).

Please advise if there is an option to have jq make changes on the file directly (similar to sed -i).

推荐答案

这篇文章解决了 sed 没有等效的-i"选项的问题,特别是描述的情况:

This post addresses the question about the absence of the equivalent of sed's "-i" option, and in particular the situation described:

我有一堆文件,将每个文件写入一个单独的文件并不容易.

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

有多种选择,至少如果您在 Mac 或 Linux 或类似环境中工作.它们的优缺点讨论在backreference/2011/01/29/就地编辑文件/所以我将只关注三种技术:

There are several options, at least if you are working in a Mac or Linux or similar environment. Their pros and cons are discussed at backreference/2011/01/29/in-place-editing-of-files/ so I'll focus on just three techniques:

一种是简单地使用&&"大致如下:

One is simply to use "&&" along the lines of:

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

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

Another is to use the sponge utility (part of GNU moreutils):

jq ... INPUT | sponge INPUT

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

The third option might be useful if it is advantageous to avoid updating a file if there are no changes to it. Here is a script which illustrates such a function:

#!/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

更多推荐

Jq 直接替换文件上的文本(如 sed

本文发布于:2023-11-24 14:14:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1625548.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本   文件   Jq   sed

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!