Home > Software engineering >  Print two strings with new lines into the table
Print two strings with new lines into the table

Time:08-17

I have two strings that I wish to print in to table.

string1="HEADER1\ndata1\ndata2"
string2="HEADER2\ndata3\ndata4"

How can I get this output in bash:

HEADER1   HEADER2
data1     data3
data2     data4

I try:

echo "$string1  $string2"

but I get totally mess.. Is there some command to print strings in columns..?

CodePudding user response:

Something along this:

paste <(echo "$string1") <(echo "$string2") | column -t

CodePudding user response:

You use csv or some other delimiter a bit more easily.

string1="HEADER1,data1,data2"

h1=$(echo "${string1}" | cut -d',' -f1)
d1=$(echo "${string1}" | cut -d',' -f2)
d2=$(echo "${string1}" | cut -d',' -f3)

cat << EOF >> file
"${h1}"

"${d1}"
"${d2}"
EOF

CodePudding user response:

Convert them to an array and loop over it like this:

string1="HEADER1\ndata1\ndata2"
string2="HEADER2\ndata3\ndata4"

arr=( $(printf "$string1 $string2") )

for ((i=0,j=3; i<3; i  ,j  )); {
    printf "${arr[$i]}\t${arr[$j]}\n"
}

Result:

HEADER1 HEADER2
data1   data3
data2   data4
  • Related