我有一个需要在特定条件下更新的 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/