Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the output of jq in single line?

Tags:

amazon-ec2

jq

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..
like image 744
Grin like a Cheshire cat Avatar asked Oct 19 '25 04:10

Grin like a Cheshire cat


2 Answers

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

like image 188
l0b0 Avatar answered Oct 22 '25 03:10

l0b0


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
like image 29
peak Avatar answered Oct 22 '25 04:10

peak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!