Search code examples
awkconcatenationend-of-line

Concatenate two lines on condition with awk


I'm trying to concatenate two lines when the number of fiels does not match a given number.

Here is an example of input file:

1, z
2
3
4
5, w
6
7

and here is the result I want:

1, z 2
3
4
5, w 6
7

I tried the following code:

awk '
{
   if (NF!=1){
   first=$0
   getline
   print first" ",$0}
   else {print $0}
}' $1

Here is what I obtain:

 2 z
3
4
 6 w
7

I don't understand why I get the next line first and then only the second field of the first line.


Solution

  • A much more shorter version would be

    $ awk 'ORS=NF == 1?"\n":FS' input
    1, z 2
    3
    4
    5, w 6
    7
    
    • ORS is output field separator

    • FS field separator, which is space by default

    • NF == 1?"\n":FS' if NF, number of fields equals to 1 then ORS is set to \n else is set to FS