Reza
Reza

Reputation: 203

Concatenation of lines

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

Answers (5)

RARE Kpop Manifesto
RARE Kpop Manifesto

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

fedorqui
fedorqui

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:
    • if the Number of Record is odd, then set it to ", ".
    • otherwise, to RS, which default to the new line.

Upvotes: 1

Dipak
Dipak

Reputation: 59

the below will also do the trick
paste -s -d ',\n' file

Upvotes: 0

bkmoney
bkmoney

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

John1024
John1024

Reputation: 113814

$ awk '{a=$0; getline; print a", "$0}' file
1, 2, 3, 4
5, 6, 7, 8
9, 10, 11, 12

How it works

  • 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

Related Questions