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"'
输出(打印到终端)
Output (printed to terminal)
{
"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).
推荐答案
您会希望在不改变环境来更新操作对象。通过让那里的管道,你改变的背景下每一个人的行动。您可以控制一些括号。
You'll want to update the action objects without changing the context. By having the pipe there, you're changing the context to each individual action. You can control that with some parentheses.
$ jq --arg age "3" \
'(.Actions[] | select(.properties.age == $age).properties.other) = "no-test"' sample.json
这应该产生:
{
"Actions": [
{
"value": "1",
"properties": {
"name": "abc",
"age": "2",
"other ": "test1"
}
},
{
"value": "2",
"properties": {
"name": "def",
"age": "3",
"other": "no-test"
}
}
]
}
您可以重定向结果以一个文件来替换输入文件。它不会做就地更新一个文件作为SED一样。
You can redirect the results to a file to replace the input file. It won't do in-place updates to a file as sed does.
这篇关于JQ代替直接在文本文件(像sed -i)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!