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?
Asked
Active
Viewed 2.8k times
37
-
possible duplicate of [Concise and portable "join" on the Unix command-line](http://stackoverflow.com/questions/8522851/concise-and-portable-join-on-the-unix-command-line) – Michael J. Barber Jan 24 '12 at 13:09
-
2@MichaelJ.Barber: The question you linked is different. The OP does not wish to join *every* line. – johnsyweb Jan 24 '12 at 13:13
-
1possible duplicate of [how to merge two files consistently line by line](http://stackoverflow.com/questions/16394176/how-to-merge-two-files-consistently-line-by-line) – kenorb Jun 17 '15 at 11:18
-
Possible duplicate of [How do I pair every two lines of a text file with Bash?](http://stackoverflow.com/questions/1513861/how-do-i-pair-every-two-lines-of-a-text-file-with-bash) – John_West Jun 20 '16 at 15:36
-
1Also http://stackoverflow.com/questions/9605232/merge-two-lines-into-one – John_West Jun 20 '16 at 15:36
5 Answers
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" " - -

synthesizerpatel
- 27,321
- 5
- 74
- 91
-
Nice! The [POSIX example](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/paste.html#tag_20_89) `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. – Ciro Santilli OurBigBook.com Jul 09 '15 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.
-
1Watch that last line if you have an odd number of input lines! `seq 11 | sed '$!N;s/\n/ /'` – johnsyweb Jan 24 '12 at 13:17
-
@Johnsyweb With GNU sed this is catered for but I've amended the solution for other sed's. – potong Jan 24 '12 at 13:23
-
1Hint: In my case, the files were created under Windows, so I needed to do this (notice the additional \r): sed '$!N;s/\r\n/ /' – Sebastien Diot Nov 02 '16 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 Apr 22 '18 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

jaypal singh
- 74,723
- 23
- 102
- 147
3
What do you mean by "in a text document"? If you are editing the file with vim, you can do:
:g/./normal J

William Pursell
- 204,365
- 48
- 270
- 300