How to get the output of jq in single line?

杀马特。学长 韩版系。学妹 提交于 2021-02-08 05:10:32

问题


I have used jq with aws cli to print the instances . Eg: Retrieve instances list

aws ec2 describe-instances --filters "Name=tag:bld_env,Values=test" --output json > all-inst.json

Jq to print instances id :

jq -r '.Reservations[].Instances[].InstanceId' all-inst.json

Output of Jq:

 i-09e0d805cc 
 i-091a61038 
 i-07d3022
 i-0428ac7c4c
 i-970dc5c4d99 
 i-014c4ea
 i-0ac924df
 i-031f6 and so on..

I want to print them in a line like this :

i-09e0d805cc,i-091a61038,i-07d3022,i-0428ac7c4c,i-970dc5c4d99,i-014c4ea,i-0ac924df,i-031f6 and so on..

回答1:


Are the angle bracket characters really there? Otherwise you can simply tr '\n' ','.




回答2:


Here are some jq-only approaches.

It's often simplest just to "join" the lines (e.g. using join(",")). This is typically done with the -r command-line option.

In cases where this is impractical or inefficient, one can use the --join (or -j) command-line option. Here are two illustrations using this approach. In neither of the examples does the output include a newline.

With a terminating comma

jq -n -j 'range(0;5) | "\(.),"'

Without a terminating comma

oneline.jq:

def oneline(f):
  foreach f as $i (null;
    if . == null then "\($i)" else ",\($i)" end;
    .);

oneline( range(0;5) )

Invocation: jq -n -j -f oneline.jq

Output:

0,1,2,3,4


来源:https://stackoverflow.com/questions/44133851/how-to-get-the-output-of-jq-in-single-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!