由于它是 JSON,因此您可以使用 jq
:
cfg=/home/users/user/config.cfg
jq '.Data[]."User-Data" = "Clear"' "$cfg" | sponge "$cfg"
( sponge
来自 moreutils
包。或者参见: jq 直接在文件上替换文本(如 sed -i) )
jq
默认情况下将漂亮地打印其输出:
{
"Name": "John Snow",
"Email": "[email protected]",
"Data": [
{
"User-Data": "Clear",
"Login-Data": "data-20240601180000",
"Cred-Data": "data-CR0909123"
},
{
"User-Data": "Clear",
"Login-Data": "data-20240601180000",
"Cred-Data": "data-CR090911212123"
},
{
"User-Data": "Clear",
"Login-Data": "data-20240601180000",
"Cred-Data": "data-CR090912123"
}
]
}
添加 -c
选项将使输出更加紧凑:
{"Name":"John Snow","Email":"[email protected]","Data":[{"User-Data":"Clear","Login-Data":"data-20240601180000","Cred-Data":"data-CR0909123"},{"User-Data":"Clear","Login-Data":"data-20240601180000","Cred-Data":"data-CR090911212123"},{"User-Data":"Clear","Login-Data":"data-20240601180000","Cred-Data":"data-CR090912123"}]}
如果必须使用 sed
,您可以尝试使用 GNU sed:
sed -Ei 's/("User-Data"\s*:\s*")(\\"|[^"])*/\1Clear/g' "$cfg"
→
{"Name": "John Snow","Email": "[email protected]","Data": [{"User-Data": "Clear","Login-Data": "data-20240601180000","Cred-Data": "data-CR0909123"},{"User-Data": "Clear","Login-Data": "data-20240601180000","Cred-Data": "data-CR090911212123"},{"User-Data": "Clear","Login-Data": "data-20240601180000","Cred-Data": "data-CR090912123"}]}
如果实际数据实际上不是示例中所示的单行,则 -z
添加