37

In a text document I want to concatenate every other line with the next. I guess sed is the thing to use? How would this be done?

5

5 Answers 5

32

This is easiest using paste:

paste -s -d' \n' input.txt 

Although there's a Famous Sed One-Liner (38) to emulate this as in potong's answer.

28

Unless you're really insistent that it need be sed, just pipe it through

paste -d" " - -

1
  • Nice! The POSIX example ls | paste - - - - implies that this is POSIX, although I can't find the remark that says it explicitly. Note that for files, paste a a copies it twice, likely because two file descriptors are created, while a single descriptor is used for stdin. Commented Jul 9, 2015 at 10:38
22

This might work for you:

seq 10 | sed '$!N;s/\n/ /'
1 2
3 4
5 6
7 8
9 10

$! If is not the last line,
N; append the following line to current line, and
s/\n/ / replace the first (first line's) newline with a space.

4
  • 1
    Watch that last line if you have an odd number of input lines! seq 11 | sed '$!N;s/\n/ /'
    – johnsyweb
    Commented Jan 24, 2012 at 13:17
  • @Johnsyweb With GNU sed this is catered for but I've amended the solution for other sed's.
    – potong
    Commented Jan 24, 2012 at 13:23
  • 1
    Hint: In my case, the files were created under Windows, so I needed to do this (notice the additional \r): sed '$!N;s/\r\n/ /' Commented Nov 2, 2016 at 15:01
  • Can someone explain this please? Without an explanation, I have no idea how to learn how to modify this statement for different use cases.
    – Anthony
    Commented Apr 22, 2018 at 14:10
3

Simple awk solution:

awk '{getline b;printf("%s %s\n",$0,b)}' file

Test:

[jaypal:~/Temp] seq 11 > file
[jaypal:~/Temp] awk '{getline b;printf("%s %s\n",$0,b)}' file
1 2
3 4
5 6
7 8
9 10
11 
3

What do you mean by "in a text document"? If you are editing the file with vim, you can do:

:g/./normal J

Not the answer you're looking for? Browse other questions tagged or ask your own question.