Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to merge next line to current line by keeping the next line

Tags:

vi

sed

awk

I have this:

A abc
B abc
C abc
D abc
...

and I need to have such file output:

A abc B abc
B abc C abc
C abc D abc
D abc ..
...

I tried this: sed 'N;s/\n/ /' but this removes the next line.

like image 257
user14185365 Avatar asked Aug 29 '20 01:08

user14185365


2 Answers

With sed:

sed '1{h;$p;d;};H;x;s/\n/ /;$G' file

On reading the first line; the line is stored into hold space (h). If it is also the last line (a file consisting of one line only) then it will be printed out ($p). Otherwise, it won't be printed. Then the pattern space is deleted and next cycle is started (d).

On each subsequent line: a newline character and the line just read is appended to the hold space (H), then hold and pattern spaces are exchanged (x). The newline character is replaced with a space (s/\n/ /). If it is the last line, the line just read will be appended to the current pattern space with a leading newline ($G).

like image 69
M. Nejat Aydin Avatar answered Oct 11 '22 17:10

M. Nejat Aydin


Could you please try following, written based on shown samples. Written and tested it in https://ideone.com/6BGYTy

awk 'prev{print prev,$0} {prev=$0}' Input_file

OR in case you want to print last line then try:

awk 'prev{print prev,$0} {prev=$0} END{print}'  Input_file

Explanation: simply checking condition if prev is not null then print prev and current line. Then setting prev's value to current line. So in very first line it wouldn't print anything but from 2nd line onwards it will print lines as per OP's shown samples.

like image 4
RavinderSingh13 Avatar answered Oct 11 '22 18:10

RavinderSingh13