Fetching a set of lines with start and end

Hi Folks,

Need help in fetching a group of lines with a start and end strings. Example is shown below.

start#morning
tea
jog
breakfast
end

start#afternoon
lunch
work
chat
end

start#evening
snacks
tea
chat
end

i need to fetch lines "start" till "end" wherever the word "tea" is available. so my output will be like below.

start#morning
tea
jog
breakfast
end

start#evening
snacks
tea
chat
end

Thanks in advance for your help guys.

awk  '/tea/ {print "start" $0 "end"}' RS='start|end' file
awk '/tea/' RS= FS="\n" yourfile

or

awk '/tea/' RS= FS="\n" ORS="\n\n" yourfile
1 Like

Hi Guys,

Thanks much for the reply.

Please let me know how do i give input from another file to this awk. I tried the below but didn't work.

for i in `cat input.txt`
do
awk '/$i/ {print "start" $0 "end"}' RS='start|end' file.txt >> output.txt
done

You can give a try to

awk 'NR==FNR{a[$0];next}{for(i in a) if($0~i) {print $0;next}}' input.txt RS= FS="\n" ORS="\n\n" yourfile

I haven't tried it so it may require some fix

To get shell variables into awk it's easiest to use -v.

Similar to:

while read srch
do
   awk -vval=$srch '$0 ~ val {print "start" $0 "end"}' RS='start|end' file.txt
done << input.txt >> output.txt

You meant :

...
awk -vval=$srch '$0 ~ val .... 
...
1 Like