P....
P....

Reputation: 18411

Chop a row into multiple rows using awk

I am trying to chop a line into multiple lines using awk. After every two words.

Input:

hey there this is a test 

Output:

hey there
this is
a test

I am able to achieve it using xargs ,as follow:

echo hey there this is a test |xargs -n2
hey there
this is
a test

However I am curious to know how to achive this using awk. Here is command I am using, which of course didn't gave expected result.

echo hey there this is a test | awk '{ for(i=1;i<=NF;i++) if(i%2=="0") ORS="\n" ;else ORS=" "}1'
hey there this is a test

And

echo hey there this is a test | awk '{$1=$1; for(i=1;i<=NF;i++) if(i%2==0) ORS="\n" ;else ORS=" "}{ print $0}'
hey there this is a test

Need to know what is conceptually wrong in above awk command and how it can be modified to give correct output. Assume input is of single line.

Thanks and Regards.

Upvotes: 2

Views: 197

Answers (3)

James Brown
James Brown

Reputation: 37454

Another flavour of @krzyk's version:

$ awk 'BEGIN {RS=" "} {ORS="\n"} NR%2 {ORS=" "} 1' test.in
hey there
this is
a test

$

Maybe even:

awk 'BEGIN {RS=" "} {ORS=(ORS==RS?"\n":RS)} 1' test.in

They both do leave an ugly enter in the end, though.

Upvotes: 1

anubhava
anubhava

Reputation: 785721

Using awk you can do:

s='hey there this is a test'
awk '{for (i=1; i<=NF; i++) printf "%s%s", $i, (i%2 ? OFS : ORS)}' <<< "$s"

hey there
this is
a test

Upvotes: 3

Krzysztof Krasoń
Krzysztof Krasoń

Reputation: 27496

First you want OFS (field separator) not ORS (record separator). And your for is in the end setting a single ORS, it iterates over all fields and sets the ORS value back and forth between " " and "\n" and at the end only one value will be there.

So what you really want is to operate on records (normally those are lines) instead of fields (normally spaces separate them).

Here's a version that uses records:

echo hey there this is a test | awk 'BEGIN {RS=" "} {if ((NR-1)%2 == 0) { ORS=" "} else {ORS="\n"}}1' 

Result:

hey there
this is
a test

Upvotes: 2

Related Questions