Jiayi Guo
Jiayi Guo

Reputation: 103

Separate output of awk script with "space" not "enter"

I know normally the output of an awk script was separated with enter. For example the script below:

awk '{print $1}' f.txt

The file f.txt's content is like:

awk bwk cwk
dwk ewk fwk
gwk hwk iwk

Then the output of the script would be like:

awk
dwk
gwk

Is there any way to get the output like

awk dwk gwk

?

Upvotes: 1

Views: 705

Answers (3)

Ed Morton
Ed Morton

Reputation: 203169

You need this:

awk '{printf "%s%s",(++n==1?"":" "),$1} END{print ""}' file

or if you prefer:

awk '{printf "%s%s",ofs,$1; ofs=OFS} END{print ""}' file

to avoid adding an undesirable space character at the end of the line and to terminate with a newline.

Upvotes: 1

chooban
chooban

Reputation: 9256

One way is to manipulate the Output Field Separator; the OFS.

awk 'BEGIN {ORS = " "} {print $1}' f.txt

By default, the ORS is a newline, but this sets it to a space.

Upvotes: 2

suspectus
suspectus

Reputation: 17258

you do so can using printf:

awk '{printf $1" "}' f.txt

Unlike print the printf function in awk does not add a newline. The " " following printf gives the required spacing character after each field.

Upvotes: 2

Related Questions