我的用例是,我有一个json文件,其中包含以下内容:
{
"environment": {
"cf_org": "EMPTY",
"cf_shared_space": "EMPTY",
"cf_user_name": "EMPTY",
"cf_home_dir": "EMPTY",
"tenant_id": "EMPTY"
}
}
我想用" tenant_id":"替换行" tenant_id":" EMPTY" "
我使用以下代码:
sed -i "/tenant_id/c\ \"tenant_id\" : "" $MYFILE.json
无法使其正常工作。
注意:替换字符串是" tenant_id":"" (所有内容都以粗体突出显示,包括引号)
答案 0 :(得分:4)
使用sed
,这对我来说更简单:
sed -i 's/"tenant_id": "EMPTY"/"tenant_id": ""/' $MYFILE.json
更简单,不需要引用:
sed -i "/tenant_id/s/EMPTY//" $MYFILE.json
答案 1 :(得分:4)
使用jq:
split
否则GNU awk和$ awk '{
split($0,a,": *",seps) # consider comma separator with : for line endings
if(a[1]~/\"tenant_id\"/)
a[2]="\"\""
print a[1] seps[1] a[2]
}' file
{
"environment": {
"cf_org": "EMPTY",
"cf_shared_space": "EMPTY",
"cf_user_name": "EMPTY",
"cf_home_dir": "EMPTY",
"tenant_id": ""
}
}
:
not
答案 2 :(得分:2)
关注awk
可能对您有帮助。
awk -v s1="\"" '/"tenant_id": "EMPTY"/{$0=s1 "tenant_id" s1 ": " s1 s1} 1' Input_file
答案 3 :(得分:0)
awk '{sub(/id": "EMPTY"/,"id\": \"\"")}1' file
output
{
"environment": {
"cf_org": "EMPTY",
"cf_shared_space": "EMPTY",
"cf_user_name": "EMPTY",
"cf_home_dir": "EMPTY",
"tenant_id": ""
}
}