Three tricks to get two commands output in single row. Normally two commands outputs will be always separated by carriage return in Linux terminal.
One of the major hurdle in scripting is to get your outputs formatted well according to requirement. In Linux/Unix each command stdout its output always in new line. This is hurdle in many situations where coder wants two outputs, two terms, two variables in single row for example csv format. In this post we will see how to present two or more commands output in single row.
Read also : Scripting related posts
Normally when we execute more than one command, they will display outputs in different rows:
# date ; hostname Sat Dec 24 01:35:50 EDT 2016 testsrv2 # echo text1; echo text2; echo text3 text1 text2 text3
In above example commands have outputs per row. We are going to accomplish all outputs in one row using below tricks.
Using translate function. AS I said earlier each command output is accompanied with carriage return. We will be translating carriage return with tab character hence getting two or more commands output in a single row.
# (date; hostname) |tr '\n' '\t' Sat Dec 24 01:36:22 EDT 2016 testsrv2 # (echo text1; echo text2; echo text3) |tr '\n' '\t' text1 text2 text3
By passing outputs to translate function we achieved single row output. Here we instructed tr function to translate all carriage returns (\n) to tab (\t).
If you want output in CSV format (comma seprated value) then replace tab with comma and you will get it.
# (date; hostname) |tr '\n' ',' Sat Dec 24 01:43:09 EDT 2016,testsrv2, # (echo text1; echo text2; echo text3) |tr '\n' ',' text1,text2,text3,
You can observe one trailing comma which shows every command output ends with \n and hence it gets replaced by ,
By defining each command output as variable. Here we will store output of each command in one variable and then we will echo those variables in single line.
# mydate=`date` # myname=`hostname` # echo $myname $mydate testsrv2 Sat Dec 24 01:46:04 EDT 2016
Here we stored date and hostname command’s output in mydate and myname variables. In last command we echoed both variables with space in between. Note that commands output can be stored in variable by executing command using back ticks (in-line execution)!
By echoing in-line execution outputs. In-line execution i.e. using back ticks to execute commands within another command. We will be using this trick to echo outputs in single row.
# echo "`date` `hostname`" Sat Dec 24 01:50:36 EDT 2016 testsrv2
In above example, first we have executed commands and got outputs. But those outputs are fed into echo command. Hence echo command stdout them in single row.
# echo "`echo text1` `echo text2` `echo text3`" text1 text2 text3
Make a note that we executed each command in separate back tick quotes.