Reputation: 59
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.
Upvotes: 0
Views: 684
Reputation: 26667
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
Upvotes: 1
Reputation: 41446
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)
Upvotes: 0
Reputation: 185005
Try doing this :
awk 'NF!=1{printf "%s ", $0;next}1' file
Output :
1, z 2
3
4
5, w 6
7
Upvotes: 0