[英]How to replace parameter of a json file by a shell script?
Let's say 123.json with below content:假设 123.json 具有以下内容:
{
"LINE" : {
"A_serial" : "1234",
"B_serial" : "2345",
"C_serial" : "3456",
"X_serial" : "76"
}
}
If I want to use a shell script to change the parameter of X_serial
by the original number +1 which is 77 in this example.如果我想使用 shell 脚本将
X_serial
的参数更改为原始数字 +1,在本例中为 77。 I have tried the below script to take out the parameter of X_serial
:我试过下面的脚本来取出
X_serial
的参数:
grep "X_serial" 123.json | awk {print"$3"}
which outputs 76
.输出
76
。 But then I don't know how to make it into 77 and then put it back to the parameter of X_serial
.但是后来不知道怎么弄成 77 再放回
X_serial
的参数。
It's not a good idea to use line-oriented tools for parsing/manipulating JSON data.使用面向行的工具来解析/操作 JSON 数据不是一个好主意。 Use jq instead, for example:
请改用jq ,例如:
$ jq '.LINE.X_serial |= "\(tonumber + 1)"' 123.json
{
"LINE": {
"A_serial": "1234",
"B_serial": "2345",
"C_serial": "3456",
"X_serial": "77"
}
}
This simply updates .LINE.X_serial
by converting its value to a number, increasing the result by one, and converting it back to a string.这只是通过将
.LINE.X_serial
的值转换为数字、将结果加一并将其转换回字符串来更新 .LINE.X_serial。
You need to install powerful JSON querying processor like jq processor.您需要安装强大的 JSON 查询处理器,如 jq 处理器。 you can can easily install from here
您可以从这里轻松安装
once you install jq processor, try following command to extract the variable from JSON key value安装 jq 处理器后,尝试以下命令从 JSON 键值中提取变量
value=($(jq -r '.X_serial' yourJsonFile.json))
you can modify the $value
as you preferred operations您可以根据自己喜欢的操作修改
$value
sed or perl , depending on whether you just need string substitution or something more sophisticated, like arithmetic. sed或perl ,具体取决于您是否只需要字符串替换或更复杂的东西,例如算术。
Since you tried grep and awk, let's start with sed:既然您尝试了 grep 和 awk,让我们从 sed 开始:
In all lines that contain TEXT, replace foo with bar在所有包含 TEXT 的行中,将 foo 替换为 bar
sed -n '/TEXT/ s/foo/bar/ p'
So in your case, something like:所以在你的情况下,类似:
sed -n '/X_serial/ s/\"76\"/\"77\"/ p'
or或者
$ cat 123.json | sed '/X_serial/ s/\"76\"/\"77\"/' > new.json
This performs a literal substiution: "76" -> "77"这执行了文字替换:“76”->“77”
If you would like to perform arithmetic, like "+1" or "+10" then use perl not sed:如果您想执行算术运算,例如“+1”或“+10”,请使用perl而不是 sed:
$ cat 123.json | perl -pe 's/\d+/$&+10/e if /X_serial/'
{
"LINE" : {
"A_serial" : "1234",
"B_serial" : "2345",
"C_serial" : "3456",
"X_serial" : "86"
}
}
This operates on all lines containing X_serial (whether under "LINE" or under something else), as it is not a json parser.这适用于所有包含 X_serial 的行(无论是在“LINE”下还是在其他东西下),因为它不是 json 解析器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.