

echo 'foosomethingbar' | grep -Po 'foo\K.*?(?=bar)' To get a substring only between two patterns, you can add Positive Lookahead into the mix. So you could do: echo 'foosomething' | grep -Po '\w+\Ksomething' Number between them doesn't have a fixed length, while it can't be done with \K since we need "foo"Īny further suggestions are still appreciated :)Īfter some testing I found out, that the pattern inside the look-behind assertion needs to be fixed length (something like (? grep: lookbehind assertion is not fixed length There is no way to match all above examples while output "foobar", since the Id like to filter the content of a log of a pom.xml file using a regex.

If "foo" and "bar" are place-holders for words that don't always have the same length, The best way so far is either using perl or combine a combination of look-behind assertions and the \K but it still seems to have some limitations. Sometimes 'PCRE style' is also used to refer to, e.g. Will not return the letter "a", only the digit following it, but it needs a fixed length, for example it cannot be used as: (?<=\w+)\d 1 Answer Sorted by: 7 PCREs are not literally perl they use a stand-alone C library, libpcre. The problem is nearly solved using "look-behind assertions" such as: (?<=a)\d A pattern consists of operators, constructs literal characters, and meta-characters, which have special meaning. I need to able to get any part of the match, for instance: ~]# ~]# echo $var |grep -oP "(a)\d"īut the wanted output in this case would be "a" A regular expression or regex is a pattern that matches a set of strings. These can be combined using look-around assertions (described under Extended Patterns in the perlre manpage) to remove part of the grep pattern from what is determined to have matched for the purposes of -o. Is not really the solution, since I don't necessarily need the last part of the match. GNU grep has the -P option for perl-style regexes, and the -o option to print only what matches the pattern. Probably it's also possible without the -P (some not-perl regex format), I'm thankful for every answer :)
#Grep perl regex full#
I also tried a non-capturing group to ignore the "a" in the output, but no effect in perl regex: '(?:a)\d'įor reference, this is the full command in my terminal: ~]# ~]# echo $var |grep -oP "a(\d)" Now what I want to do is match only "a" follow by any digit, but I only want it to return the number after "a"Īnd since I only need the digit, I tried with 'a(\d)'Īnd maybe it did capture it somewhere, but I don't know where, the output here is still "a1"

So I've done some research on the subject and I didn't quite find the perfect solution.įor example I have a string inside a variable.
