In the two commands above, we passed two options to the paste command: -s and -d. The paste command can merge lines from multiple input files. By default, it merges lines in a way that entries in the first column belong to the first file, those in the second column are for the second file, and so on.
The traditional way of using paste command with "-s" option. "-d" in paste can take multiple delimiters. The delimiters specified here are comma and a newline character. This means while joining the first and second line use comma, and the second and third line by a newline character.
sed operates by performing the following cycle on each lines of input: first, sed reads one line from the input stream, removes any trailing newline, and places it in the pattern space. Then commands are executed; […]. Add a newline to the pattern space, then append the next line of input to the pattern space.
To merge lines of files, we use the paste command in the Linux system. The paste command is used to combine files horizontally by outputting lines consisting of the sequentially corresponding lines from each FILE, separated by TABs to the standard output.
paste
is good for this job:
paste -d " " - - < filename
awk:
awk 'NR%2{printf "%s ",$0;next;}1' yourFile
note, there is an empty line at the end of output.
sed:
sed 'N;s/\n/ /' yourFile
Alternative to sed, awk, grep:
xargs -n2 -d'\n'
This is best when you want to join N lines and you only need space delimited output.
My original answer was xargs -n2
which separates on words rather than lines. -d
(GNU xargs option) can be used to split the input by any singular character.
There are more ways to kill a dog than hanging. [1]
awk '{key=$0; getline; print key ", " $0;}'
Put whatever delimiter you like inside the quotes.
References:
Here is my solution in bash:
while read line1; do read line2; echo "$line1, $line2"; done < data.txt
Here is another way with awk
:
awk 'ORS=NR%2?FS:RS' file
$ cat file
KEY 4048:1736 string
3
KEY 0:1772 string
1
KEY 4192:1349 string
1
KEY 7329:2407 string
2
KEY 0:1774 string
1
$ awk 'ORS=NR%2?FS:RS' file
KEY 4048:1736 string 3
KEY 0:1772 string 1
KEY 4192:1349 string 1
KEY 7329:2407 string 2
KEY 0:1774 string 1
As indicated by Ed Morton in the comments, it is better to add braces for safety and parens for portability.
awk '{ ORS = (NR%2 ? FS : RS) } 1' file
ORS
stands for Output Record Separator. What we are doing here is testing a condition using the NR
which stores the line number. If the modulo of NR
is a true value (>0) then we set the Output Field Separator to the value of FS
(Field Separator) which by default is space, else we assign the value of RS
(Record Separator) which is newline.
If you wish to add ,
as the separator then use the following:
awk '{ ORS = (NR%2 ? "," : RS) } 1' file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With