Bash CLI 從指令輸出中刪除引號

Bash CLI 從指令輸出中刪除引號

jq我正在嘗試使用per加載 JSON 文件這裡。這非常簡單且有效:

$ cat ~/Downloads/json.txt | jq '.name'
"web"

但是,我需要將此變數的輸出分配給命令。我嘗試這樣做並且有效:

$ my_json=`cat ~/Downloads/json.txt | jq '.name'`
$ myfile=~/Downloads/$my_json.txt
$ echo $myfile
/home/qut/Downloads/"web".txt

但我想要/home/qut/Downloads/web.txt

如何刪除引號,即更改"web"web

答案1

您可以使用t刪除引號的命令:

my_json=$(cat ~/Downloads/json.txt | jq '.name' | tr -d \")

答案2

在 的特殊情況下jq,您可以指定輸出應位於生的格式:

   --raw-output / -r:

   With this option, if the filter´s result is a string then  it  will
   be  written directly to standard output rather than being formatted
   as a JSON string with quotes. This can be useful for making jq fil‐
   ters talk to non-JSON-based systems.

為了說明如何使用範例json.txt文件你的連結

$ jq '.name' json.txt
"Google"

然而

$ jq -r '.name' json.txt
Google

答案3

使用本機 shell 前綴/後綴刪除功能更簡單、更有效率:

my_json=$(cat ~/Downloads/json.txt | jq '.name')
    temp="${my_json%\"}"
    temp="${temp#\"}"
    echo "$temp"

來源https://stackoverflow.com/questions/9733338/shell-script-remove-first-and-last-quote-from-a-variable

答案4

你可以eval echo這樣使用:

my_json=$(eval echo $(cat ~/Downloads/json.txt | jq '.name'))

但這並不理想——很容易導致錯誤和/或安全缺陷。

相關內容