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?
-
possible duplicate of Concise and portable "join" on the Unix command-line– Michael J. BarberCommented Jan 24, 2012 at 13:09
-
2@MichaelJ.Barber: The question you linked is different. The OP does not wish to join every line.– johnsywebCommented Jan 24, 2012 at 13:13
-
1possible duplicate of how to merge two files consistently line by line– kenorbCommented Jun 17, 2015 at 11:18
-
Possible duplicate of How do I pair every two lines of a text file with Bash?– John_WestCommented Jun 20, 2016 at 15:36
-
1Also stackoverflow.com/questions/9605232/merge-two-lines-into-one– John_WestCommented Jun 20, 2016 at 15:36
Add a comment
|
5 Answers
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.
Unless you're really insistent that it need be sed, just pipe it through
paste -d" " - -
-
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
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/ /'
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.– potongCommented Jan 24, 2012 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/ /' 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.– AnthonyCommented Apr 22, 2018 at 14:10
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
What do you mean by "in a text document"? If you are editing the file with vim, you can do:
:g/./normal J