Concatenate two lines on condition with awk

671 views Asked by At

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.

3

There are 3 answers

4
nu11p01n73R On BEST ANSWER

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

0
Gilles Quénot On

Try doing this :

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

Output :

1, z 2
3
4
5, w 6
7
3
Jotne On

This may do:

awk '{printf "%s%s",$0,(NF>1?FS:RS)}' file
1, z 2
3
4
5, w 6
7

It prints newline if there is one field and else one blank (Field Separator)