Search code examples
stringbashline

How to output lines into one string separated by space (bash)


I have this construction in Bash

while read line
do
    echo $line | while read  a b c d e f g
    do
        if [ $e != "0" ]; then
        echo -en "|'$a'=;$g;$f;;"
        fi
    done
done < /tmp/res6

Which cat this text

mem_total_app_1 5034876928  + 384000 = 5035260928       mysqld
mem_total_app_2 2994008064  + 108532736 = 3102540800    /usr/sbin/amavi(91)
mem_total_app_3 648744960  + 103424 = 648848384 redis-server
mem_total_app_4 541454336  + 58354688 = 599809024       php-fpm7.2(26)

and output to this

|'mem_total_app_1'=;mysqld;5035260928;;
|'mem_total_app_2'=;/usr/sbin/amavi(91);3102540800;;
|'mem_total_app_3'=;redis-server;648848384;;
|'mem_total_app_4'=;php-fpm7.2(26);599809024;;

I would like to have the output in one string separated by space. Like this

|'mem_total_app_1'=;mysqld;5035260928;; 'mem_total_app_2'=;amavi(91);3102540800;; 'mem_total_app_3'=;redis-server;648848384;; 'mem_total_app_4'=;php-fpm7.2(26);599809024;;

Could somebody prompt me, please?


Solution

  • Try printf

    The printf command provides a method to print preformatted text similar to the printf() system interface (C function). It's meant as successor for echo and has far more features and possibilities.

    printf "|"
    while read line
    do
        echo $line | while read  a b c d e f g
        do
            if [ $e != "0" ]; then
            printf " '$a'=;$g;$f;;"
            fi
        done
    done  < /tmp/res6
    

    Output :-

    | 'mem_total_app_1'=;mysqld;5035260928;; 'mem_total_app_2'=;/usr/sbin/amavi(91);3102540800;; 'mem_total_app_3'=;redis-server;648848384;; 'mem_total_app_4'=;php-fpm7.2(26);599809024;;