Amit Manchanda Amit Manchanda - 6 months ago 13
Bash Question

How to print the string preceding a specific word in shell?

I have a string and I want to print all the substrings that end with a specific word in shell, example



This is a echo test example echo please help me echo with this echo question


I want its output to be

This is a echo
This is a echo test example echo
This is a echo test example echo please help me echo
This is a echo test example echo please help me echo with this echo

Answer

With GNU sed :

$ sed -n 's/ echo/&\n/g;:a;/echo\n/P;s/echo\n/echo/;ta' file
This is a echo
This is a echo test example echo
This is a echo test example echo please help me echo
This is a echo test example echo please help me echo with this echo