Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

processing alternate line bash

Tags:

sed

awk

I have a file like this

line1
this is line1
line2
this is line2
line3
this is line3

I wanted to use awk or sed to remove trailing newline characters at every alternate line to merge them like this

line1: this is line1    
line2: this is line2
line3: this is line3

How do I do it using awk or sed

like image 885
marc Avatar asked Feb 21 '23 07:02

marc


2 Answers

$ cat input 
line1
this is line1
line2
this is line2
line3
this is line3
$ awk 'NR%2==1 {prev=$0} NR%2==0 {print prev ": " $0} END {if (NR%2==1) {print $0 ":"}}' input
line1: this is line1
line2: this is line2
line3: this is line3
$ 
like image 179
sarnold Avatar answered Feb 23 '23 12:02

sarnold


Using sed:

sed -n '${s/$/:/p};N;s/\n/: /p' inputFile

For in-place editing with backup of original file,

sed -n -i~ '${s/$/:/p};N;s/\n/: /p' inputFile
like image 31
Prince John Wesley Avatar answered Feb 23 '23 13:02

Prince John Wesley