Reputation: 203
I need to join every other line in a file with the line after it.
1, 2
3, 4
5, 6
7, 8
9, 10
11, 12
The output should be like:
1, 2, 3, 4
5, 6, 7, 8
9, 10, 11, 12
I have used awk '{getline b;printf("%s,%s\n",$0,b)}' file
. However, the output is:
1, 2
,3, 4
5, 6
,7, 8
9, 10
,11, 12
I wonder how each line can be concatenated with the line after it.
Upvotes: 1
Views: 93
Reputation: 2815
don't do math when none is called for :
{m,g}awk 'ORS = RS<ORS ? RS :", "' FS='^$'
1, 2, 3, 4
5, 6, 7, 8
9, 10, 11, 12
Upvotes: 0
Reputation: 289515
The classical and idiomatic way to do it with awk
is like follows:
$ awk 'ORS=NR%2?", ":RS' file
1, 2, 3, 4
5, 6, 7, 8
9, 10, 11, 12
This is based on an example in Idiomatic awk and works as follows:
ORS=NR%2?", ":RS
set the Output Record Separator to either ", " or new line, depending on which line are we considering:
Upvotes: 1
Reputation: 1256
You can use
sed 'N;s/\n/, /' file
This N appends the next line and s command substitutes the newline with a comma and space.
The output is:
1, 2, 3, 4
5, 6, 7, 8
9, 10, 11, 12
Upvotes: 3
Reputation: 113814
$ awk '{a=$0; getline; print a", "$0}' file
1, 2, 3, 4
5, 6, 7, 8
9, 10, 11, 12
a=$0
This saves the current line in variable a
.
getline
This reads the next line into $0
.
print a", "$0
This prints them both side by side with a comma between them.
Upvotes: 3