Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep - regular expression - match till a specific word

Tags:

regex

grep

bash

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.

like image 566
thefourtheye Avatar asked Jan 26 '26 06:01

thefourtheye


1 Answers

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
like image 191
Kent Avatar answered Jan 27 '26 22:01

Kent