簡體   English   中英

sed命令問題

[英]sed command issues

背景

原始json( test.json ): {"rpc-password": "password"}

預期更改的json: {"rpc-password": "somepassword"}

replace_json_str是用於使用sedpassword替換為somepassword的函數。

replace_json_str() {
    x=$1
    sed -i -e 's/\({ "'"$2"'":\)"[^"]*" }/\1"'"$3"'" }/g' $x
}

單元測試: replace_json_str test.json rpc-password somepassword

問題

運行上述測試后,我得到一個名為test.json-e的文件,該文件的內容與運行測試之前的文件相同,為什么?

有一個方便的命令行json工具jq

cat input.json
{"rpc-password": "password"}

貓update_json.sh

givenkey=$1
givenvalue=$2

inputfile=input.json
outfile=output.json

cat $inputfile  | jq .   #  show input json

jq --arg key1 "$givenkey" --arg val1 "$givenvalue"  '.[$key1] = $val1' "$inputfile" > "$outfile"

cat "$outfile" | jq .     #  render output json

記住jq可以處理多個這樣的鍵值更新...執行它

update_json.sh  rpc-password somepassword
{
  "rpc-password": "password"
}
{
  "rpc-password": "somepassword"
}

取決於您使用的sed

您運行的命令將與GNU sed一起使用。

但是BSD sed不允許對-i使用空參數,並且如果您運行相同的命令,它將使用下一個參數-e作為備份文件。

此外,模式中空格的位置與示例JSON不匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM