Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to print the awk output in the same line

The awk output looks like:

awk '{print $2}'
toto
titi
tata

I want to dispay the output of awk in the same line with space as separator instead of new line

awk [option] '{print $2}'
toto titi tata

Is it possible to do that?

like image 410
MOHAMED Avatar asked Jun 20 '14 16:06

MOHAMED


People also ask

How do I print an awk output on one line?

To print a blank line, use print "" , where "" is the empty string. To print a fixed piece of text, use a string constant, such as "Don't Panic" , as one item. If you forget to use the double-quote characters, your text is taken as an awk expression, and you will probably get an error.

Does awk work line by line?

Default behavior of Awk: By default Awk prints every line of data from the specified file. In the above example, no pattern is given. So the actions are applicable to all the lines. Action print without any argument prints the whole line by default, so it prints all the lines of the file without failure.

What does awk '{ print $2 }' mean?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output.

What is awk '{ print $1 }'?

If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.


3 Answers

From the manpage:

ORS         The output record separator, by default a newline.

Therefore,

awk 'BEGIN { ORS=" " }; { print $2 }' file
like image 112
Manny D Avatar answered Sep 29 '22 07:09

Manny D


You can always use printf to control the output of awk

awk '{printf "%s ",$2}' file
toto titi tata 
like image 42
Jotne Avatar answered Sep 25 '22 07:09

Jotne


OR you can use paste

awk '{print $2}' FILE |paste -sd " "
like image 34
Baba Avatar answered Sep 29 '22 07:09

Baba