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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With