Extract all the lines in between of 2 patterns and merge them

Hi,

I have a file with many lines and need to extract lines between 2 patterns (AAA and BBB) and merge all the in-between lines into single line separated by space.

$ cat file1
blah blah blah
blah AAA
1
2
3
blah BBB
blah blah blah
blah blah blah
blah blah blah
AAA
5
6
blah blah BBB
blah blah blah

admin@admin-PC /tmp
$

And I tried the below with little success :slight_smile:

admin@admin-PC /tmp
$ awk '/AAA/{a=1;next}/BBB/{a=0}a' file1
1
2
3
5
6

admin@admin-PC /tmp

But I need the output as below:

1 2 3
5 6

Please advise, thanks a lot!!

awk '/AAA/ {ok=1;next} /BBB/ {ok=0;print ""; next} {if(ok){printf("%s ", $0) } }' inputfile > newfile 

Another approach:

awk '/AAA/{f=1;next}/BBB/{print s;f=s=""}f{s=s?s OFS $0:$0}' file

Some more awk for given input

$ awk '/AAA/,/BBB/{printf /^[0-9]/? $0 OFS : /BBB/ ? RS : NULL }' file
1 2 3 
5 6 
$ awk '/AAA/{s=1}s && /^[0-9]/,/^[0-9]/{printf $0 OFS}/BBB/{s=0;printf RS}' file
1 2 3 
5 6 
$ awk '/AAA/{x=1;getline}/BBB/{printf RS;x=0}x{printf $0 OFS}' file
1 2 3 
5 6
$ awk '/AAA/,/BBB/{printf /BBB/ ? RS : gsub(/[[:alpha:]]/,x) == 0 ? $0 OFS : NULL }' file
1 2 3 
5 6 

With a trailing space:

awk '/BBB/{p=0; printf RS}p; /AAA/{p=1}' ORS=" " file

--
@Akshay:
Unless you are printing a constant, it is best to use a format string with printf .