bash 如何在jq中的每次迭代中获得换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44062915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:10:25  来源:igfitidea点击:

How to get newline on every iteration in jq

jsonbashnewlinejqoutput-formatting

提问by user3198755

I have the following file

我有以下文件

[
  {
    "id": 1,
    "name": "Arthur",
    "age": "21"
  },
  {
    "id": 2,
    "name": "Richard",
    "age": "32"
  }
]

To display login and id together, I am using the following command

要一起显示登录名和 id,我使用以下命令

$ jq '.[] | .name' test
"Arthur"
"Richard"

But when I put it in a shell script and try to assign it to a variable then the whole output is displayed on a single line like below

但是当我把它放在一个 shell 脚本中并尝试将它分配给一个变量时,整个输出就会显示在一行上,如下所示

#!/bin/bash

names=$(jq '.[] | .name' test)
echo $names

$ ./script.sh
"Arthur" "Richard"

I want to break at every iteration similar to how it works on the command line.

我想在每次迭代时中断,类似于它在命令行上的工作方式。

回答by Inian

Couple of issuesin the information you have provided. The jqfilter .[] | .login, .idwill not produce the output as you claimed on jq-1.5. For your original JSON

您提供的信息中有几个问题。该jq过滤器.[] | .login, .id,你声称上不会产生输出jq-1.5。为您的原创JSON

{  
   "login":"dmaxfield",
   "id":7449977
}
{  
   "login":"stackfield",
   "id":2342323
}

It will produce four lines of output as,

它将产生四行输出,

jq -r '.login, .id' < json
dmaxfield
7449977
stackfield
2342323

If you are interested in storing them side by side, you need to do variable interpolation as

如果您有兴趣将它们并排存储,则需要进行变量插值

jq -r '"\(.login), \(.id)"' < json
dmaxfield, 7449977
stackfield, 2342323

And if you feel your output stored in a variable is not working. It is probably because of lack of double-quotes when you tried to print the variable in the shell.

如果您觉得存储在变量中的输出不起作用。这可能是因为当您尝试在 shell 中打印变量时缺少双引号。

jqOutput=$(jq -r '"\(.login), \(.id)"' < json)
printf "%s\n" "$jqOutput"
dmaxfield, 7449977
stackfield, 2342323

This way the embedded new lines in the command output are notswallowed by the shell.

这样,命令输出中嵌入的新行就不会被 shell 吞掉。



For you updated JSON(totally new one compared to old one), all you need to do is

对于您更新JSON(与旧版本相比,全新版本),您需要做的就是

jqOutput=$(jq -r '.[] | .name' < json)
printf "%s\n" "$jqOutput"
Arthur
Richard

回答by peak

In case the .login or .id contains embedded spaces or other characters that might cause problems, a more robust approach is to ensure each JSON value is on a separate line. Consider, for example:

如果 .login 或 .id 包含可能导致问题的嵌入空格或其他字符,更可靠的方法是确保每个 JSON 值位于单独的行上。考虑,例如:

jq -c .login,.id input.json | while read login ; do read id; echo login="$login" and id="$id" ; done
login="dmaxfield" and id=7449977
login="stackfield" and id=2342323