How to Display Characters Between Two Strings – Shell Scripting

shellshell-script

I want to display all the characters in a file between strings "xxx" and "yyy" (the quotes are not part of the delimiters). How can I do that ? For example, if i have input "Hello world xxx this is a file yyy", the output should be " this is a file "

Best Answer

You can use the pattern matching flag in sed as follows:

echo "Hello world xxx this is a file yyy" | sed 's/.*xxx \(.*\)yyy/\1/'

So .*xxx will match from the beginning up to xxx. This is best shown using grep:

enter image description here

\1 is a 'Remember pattern' that remembers everything that is within \(.*\) so from xxx up to yyy but not yyy.

Finally the remembered string is printed.

Related Question