Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed merge 2 lines after a pattern

Tags:

regex

sed

I want to merge two lines after a pattern using sed (no awk please because I am using windows) so for example here is the input

pattern
XXXXXX
YYYYYY

and here is the output:

 XXXXXXYYYYYY
like image 228
Leo92 Avatar asked Aug 31 '12 09:08

Leo92


2 Answers

With sed this works:

sed -n '/pattern/ {s/.*//; N; N; s/\n//g; p;}'

Explanation

  • /pattern/ matches pattern and executes the brace block { }.
  • s/.*// deletes pattern from pattern space, a shorter but more obscure way of getting rid of pattern is to exchange pattern space and hold space with the x command.
  • N takes next line from input file and appends it to pattern space.
  • s/[\r\n]//g removes all newlines and carriage returns from pattern space.
  • p prints pattern space.

A slightly shorter solution for combining 3 lines is:

sed -n '/pattern/ {x; N; N; s/\n//g; p;}'
like image 153
Thor Avatar answered Oct 07 '22 01:10

Thor


Verified on Windows:

sed -r '1h; 1!H; ${ g; s/pattern[\r\n]+(.*)[\r\n]+(.*)/\1\2/ p}' infile

Corrected according to Multiline sed replace

like image 39
mmdemirbas Avatar answered Oct 07 '22 00:10

mmdemirbas