Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining two consecutive lines using awk or sed

Tags:

How would I join two lines using awk or sed?

I have data that looks like this:

abcd
joinabcd
efgh
joinefgh
ijkl
joinijkl

I need an output like the one below:

joinabcdabcd
joinefghefgh
joinijklijkl
like image 830
Vijay Avatar asked Jul 07 '10 12:07

Vijay


People also ask

How do you join two lines using sed?

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.

Which is faster awk or sed?

I find awk much faster than sed . You can speed up grep if you don't need real regular expressions but only simple fixed strings (option -F). If you want to use grep, sed, awk together in pipes, then I would place the grep command first if possible.

Can we use awk and sed together?

Combining the Twoawk and sed are both incredibly powerful when combined. You can do this by using Unix pipes. Those are the "|" bits between commands.


2 Answers

awk '!(NR%2){print$0p}{p=$0}' infile
like image 167
Dimitre Radoulov Avatar answered Oct 06 '22 23:10

Dimitre Radoulov


You can use printf with a ternary:

    awk '{printf (NR%2==0) ? $0 "\n" : $0}'
like image 33
Bryon Nicoson Avatar answered Oct 06 '22 22:10

Bryon Nicoson