tafelplankje
tafelplankje

Reputation: 593

bash/awk append next line if the columns is less than 4

I would like to do the following but dont know how to to this in awk. I need to append the next line if the number of columns are less than 4 (so that it matches the lines with 8 columns)

aaa2 17 79285137 bbb3 0.23 A X 5
aaa2 17 79287477 
aaa2 1 F F 5 
aaa2 17 79291434 bbb33 1 G X 5
aaa2 17 79292215 bcs23 1 Q X 5
aaa22 4 4201745 
aaa22 1 C C 5
....

to

aaa2 17 79285137 bbb3 0.23 A X 5
aaa2 17 79287477 aaa2 1 F F 5 
aaa2 17 79291434 bbb33 1 G X 5
aaa2 17 79292215 bcs23 1 Q X 5
aaa22 4 4201745  aaa22 1 C C 5
....

Upvotes: 2

Views: 1111

Answers (4)

Scrutinizer
Scrutinizer

Reputation: 9956

(Edit: I restored the ealier versions otherwise it will be difficult to follow..)

One more:

awk '{ORS=NF<4?x:RS}1' file

The above can be used if no field separator is needed between rejoined sentence parts. Here is one that would introduce a space:

awk 'ORS=NF<4?FS:RS' file

Even though the above options will work for OP's sample input, they would fail if the line that needs to be joined has fewer than 4 fields (for instance a total of lines with 2 x 3 fields that need to be joined to one line with 6 fields, which is not the case with the sample above)

That is why I added this option:

awk 'NF<4{getline $(NF+1)}1' file

I had a look at the Dimitre's link to Ed Morton's post but I think that in this case there are no real getline caveats that would apply. The fact that NF does not get updated is not problem for this application. Normally I would test success of a getline but I left that out here, because if in the hypthetical situation there would be fewer than 3 fields on the last line then the input file would be broken to begin with and none of the solutions here would provide a 100% correct answer.

Upvotes: 2

Vijay
Vijay

Reputation: 67319

awk '{if(NF<4){x=$0;f=1;next}if(f){$0=x" "$0;f=0};print}' your_file

tested:

> awk '{if(NF<4){x=$0;f=1;next}if(f){$0=x" "$0;f=0};print}' temp
aaa2 17 79285137 bbb3 0.23 A X 5
aaa2 17 79287477  aaa2 1 F F 5 
aaa2 17 79291434 bbb33 1 G X 5
aaa2 17 79292215 bcs23 1 Q X 5
aaa22 4 4201745  aaa22 1 C C 5
>

Upvotes: 1

anubhava
anubhava

Reputation: 786359

This awk will work for you:

awk '{if (pre!="") {print pre $0; pre=""} else if (NF>=4) print; else pre=$0}' in.file

Upvotes: 1

Kent
Kent

Reputation: 195289

try this line:

awk 'NF<4{printf "%s", $0;next}1' file

Upvotes: 3

Related Questions