Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine multiple lines between flags in one line in AWK

Tags:

awk

Example file:

Pattern 1

AAAAAAAAAA
BBBBBBBBBB

Pattern 2

I want to print the lines between two patterns in a file in one line. From a previous question How to print lines between two patterns, inclusive or exclusive (in sed, AWK or Perl)? I found the very nice

awk '/Pattern 1/{flag=1; next} /Pattern 2/{flag=0} flag' file

With output:

AAAAAAAAAA
BBBBBBBBBB

My desired output:

AAAAAAAAAABBBBBBBBBB
like image 595
Mike de Groot Avatar asked Mar 21 '21 21:03

Mike de Groot


1 Answers

You may use this awk:

awk '/Pattern 2/ {if (s!="") print s; s=f=""} f {s = s $0} /Pattern 1/ {f=1}' file

AAAAAAAAAABBBBBBBBBB
like image 112
anubhava Avatar answered Oct 20 '22 13:10

anubhava