3

I wrote a regular exprssion:

(?<value>(?<=start=)\d+)

I'tested it in Exprsso and it works When Itried to use it in BASH script, there are no result, althogh the data is the same as in the test with Expresso. Can a gruoping be used with grep, and return array like result?

grep -Po "(?<value>(?<=start=)\d+)" page.txt > result.txt

Is this the way it is used?

Edit - example data (working)

www.example.com/check?var=test&start=11
1
  • What do you really want to get?
    – konsolebox
    Commented Jul 16, 2014 at 15:04

3 Answers 3

4

If you're looking to get the numbers following "start=", you don't need a named capture group. You don't even need capturing parentheses, that's really what -o does. Simplify:

grep -Po '(?<=start=)\d+'

More examples would be:

echo 'some text here:11' | grep -Po '(?<=here:)\d+'
11
echo 'some text here:apple' | grep -Po '(?<=here:)\w+'
apple
0
2

The Named Capturing Group is not necessary here. Using the -o option shows only the matching part that matches the pattern, so with the combination of the Positive Lookbehind assertion and the -o command line option, you do not need a capturing group. The lookbehind does not consume characters in the string, but only asserts whether a match is possible or not.

echo 'foo.com/check?var=test&start=11' | grep -Po '(?<=start=)\d+'
# 11

Alternatively, \K resets the starting point of the reported match and any previously consumed characters are no longer included. e.g. throws away everything that it has matched up to that point.

grep -Po 'start=\K\d+'
0

Another way of doing positive lookbehind with \K:

echo 'foo.com/check?var=test&start=11' | grep -Po 'start=\K\d+'
11

Not the answer you're looking for? Browse other questions tagged or ask your own question.