grep - regular expression - match till a specific word

bash, grep, regex

Solution

this line chops leading `abc` and ending `xyz` (if there was) away, and gives you the part you need:

grep -oP '^abc\K.*?(?=xyz$|$)'

with your example:

kent$  echo "abcefghijklxyz
abcefghijkl"|grep -oP '^abc\K.*?(?=xyz$|$)'
efghijkl
efghijkl

another example with `xyz` in the middle of the text:

kent$  echo "abcefghijklxyz
abcefghijkl
abcfffffxyzbbbxyz
abcffffxyzbbb"|grep -oP '^abc\K.*?(?=xyz$|$)'
efghijkl
efghijkl
fffffxyzbbb
ffffxyzbbb

Problem

Lets say I have a file with lines like this ``` abcefghijklxyz abcefghijkl ``` I want to get only the string between `abc` and the end of the line. End of the line can be defined as the normal end of line or the string `xyz`. My question is How can I get only the matched string using `grep` and regular expressions? For example, the expected output for the two lines shown above would be ``` efghijkl efghijkl ``` I don't want the starting and ending markers. What I have tried till now ``` grep -oh "abc.*xyz" ``` I use Ubuntu 13.04 and Bash shell.

Original source