user973363
user973363

Reputation: 45

Unix - how to append next line to previous line in a file

How can i append the next line to a previous line in a file, delimited by pipe symbol?

Expectd Input -- content of input.txt

ABC    
BCD    
DEF    
EFG    
FGH    

Expectd Output -- content of output.txt

|ABC|BCD|    
|BCD|DEF|    
|DEF|EFG|    
|EFG|FGH|    
|FGH||

Upvotes: 2

Views: 1847

Answers (3)

William Pursell
William Pursell

Reputation: 212248

paste - - < input-txt

is a good start, but it does not add your desired delimiters. For that, try:

 paste - - < input-txt | awk '{$1=$1; print OFS $0 OFS}' OFS=\|

(Or any of many other ways to insert the | symbol between the fields! This version emits |FGH| instead of |FGH|| on the final line.)

Or:

 sed 1d input-txt | paste -d \| input - | sed 's/^\|$/|/g'

Upvotes: 2

slitvinov
slitvinov

Reputation: 5768

http://www.gnu.org/software/gawk/manual/html_node/Field-Separators.html

awk -v ORS="|\n" -v OFS="|" 'NR>1{print p, $1} {p=$1} END{print p, ""}' foo.txt

Or without ORS

awk -v OFS="|" 'NR>1{print p, $1, ""} {p=$1} END{print p, "", ""}' foo.txt

Upvotes: 1

iruvar
iruvar

Reputation: 23364

with bash on linux

 join -o 1.2,2.2,2.3 -t'|' -1 1 -2 1 -a 1 <(awk '{print(NR"|"$0)}' input.txt | sort -k1,1 -t'|' -n) <(awk '{print(NR - 1"|"$0"|")}' input.txt | sort -k1,1 -t'|' -n)

Upvotes: 0

Related Questions