0

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
bosonfute
  • 57
  • 7

3 Answers3

1

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

nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52
  • Thanks. But it is strange, using your suggestion, I get exactly the same (wrong) output as I mentioned in my question. – bosonfute Dec 02 '14 at 07:21
  • @bosonfute chances are that your input file may not be correctly formated as in the question. Please do check that – nu11p01n73R Dec 02 '14 at 07:23
  • @bosonfute I have tested the script in `GNU Awk 3.1.5` it works fine there though :/ – nu11p01n73R Dec 02 '14 at 07:25
  • Thanks. Weird: I tried on a different VM. All the solutions provided here, including mine that I included in my question, give the correct output. On my own computer, everything gives the wrong output (the one in my question). I don't have a strange distribution: Linux Mint (Debian) and awk version is GNU Awk 4.0.X. On the VM, it is 3.1.7. Maybe awk version is the problem. – bosonfute Dec 02 '14 at 13:50
0

Try doing this :

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

Output :

1, z 2
3
4
5, w 6
7
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
0

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)

Jotne
  • 40,548
  • 12
  • 51
  • 55
  • Thanks. But it is strange, using your suggestion, I get exactly the same (wrong) output as I mentioned in my question. – bosonfute Dec 02 '14 at 07:22
  • @bosonfute Then you indata is different from what you have posted here. PS do not use `getline`. Google `why not use getline` and you see why. – Jotne Dec 02 '14 at 07:24
  • Thanks. Good to know about getline. I'll be careful now. Still I think my problem is due to awk version, as I mentioned in my reply to nu11p01n73R. – bosonfute Dec 02 '14 at 13:58