Jq 直接替换文件上的文本(如 sed -i) [英] Jq to replace text directly on file (like 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 或类似环境中工作.它们的优缺点讨论在http://backreference.org/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 http://backreference.org/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 -i)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!