Bash CLI 从命令的输出中删除引号

ede*_*esz 21 command-line text-processing json

我正在尝试使用jqper here加载 JSON 文件。它非常简单,并且有效:

$ cat ~/Downloads/json.txt | jq '.name'
"web"
Run Code Online (Sandbox Code Playgroud)

但是,我需要将此变量的输出分配给命令。我试图这样做,这有效:

$ my_json=`cat ~/Downloads/json.txt | jq '.name'`
$ myfile=~/Downloads/$my_json.txt
$ echo $myfile
/home/qut/Downloads/"web".txt
Run Code Online (Sandbox Code Playgroud)

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

如何删除引号,即更改"web"web

Flo*_*sch 37

您可以使用tr命令删除引号:

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

  • 谢谢你的 `tr` 命令......我浏览了 4 个不同的帖子,其中有数百个赞,有人写了 40 多个字符的超级单行字来完成工作。你有正确的(可能是现代的)解决方案。 (2认同)

ste*_*ver 24

在 的特殊情况下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.
Run Code Online (Sandbox Code Playgroud)

为了说明使用链接中的示例json.txt文件:

$ jq '.name' json.txt
"Google"
Run Code Online (Sandbox Code Playgroud)

然而

$ jq -r '.name' json.txt
Google
Run Code Online (Sandbox Code Playgroud)