awk or sed to print text between the first occurance of a pattern and the last occurance of a pattern

StackOverflow https://stackoverflow.com/questions/20096639

  •  03-08-2022
  •  | 
  •  

Question

i have seen a couple of solutions to print between patterns but am unable to put things together to cater to my problem. I have a text file that contains a view definition as shown below and need to extract the definition between the first and last braces. Please note: there are open and closed braces in between which should be printed. any solution in awk or sed?

create view view_name 
as(select column1 as someDATE,
    column2,
    column3,
    substring(convert(char(19),(DATEadd(hh,8,column4)),121),12) as someTIME,
    from table_name
    where NAME in('test')
    and column5='something')

Output reqired:

select column1 as someDATE,
column2,
column3,
substring(convert(char(19),(DATEadd(hh,8,column4)),121),12) as someTIME,
from table_name
where NAME in('test')
and column5='something'
Was it helpful?

Solution

Crude but effective:

sed -n -e '/(/,/)/p' filename | sed '1s/[^(]*(//;$s/)[^)]*$//'

EDIT:

(Corrected first solution.)

More sophisticated, but pulls the whole file into the hold space at once:

sed -n 'H;${x;s/^[^(]*(//;s/)[^)]*$//;p;}' filename

OTHER TIPS

In awk:

awk '/\(/&&!x{x=1;sub(/^[^(]*\(/,"")} match($0,/\)[^)]*$/)>0&&x{printf"%s",b substr($0,1,RSTART-1);b=substr($0,RSTART)"\n";next} x{b=b$0"\n"}' filename

It buffers text since first occurrence of ( (or later appearances of )) into the b variable. When a ) later appears, it prints the buffer (and the current line up to last )), and buffers the rest of the line into b.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top