Can not extract the capture group with either sed or grep

Solution 1:

1. Use grep -Eo: (as egrep is deprecated)

echo 'employee_id=1234' | grep -Eo '[0-9]+'

1234

2. using grep -oP (PCRE):

echo 'employee_id=1234' | grep -oP 'employee_id=\K([0-9]+)'

1234

3. Using sed:

echo 'employee_id=1234' | sed 's/^.*employee_id=\([0-9][0-9]*\).*$/\1/'

1234

Solution 2:

To expand on anubhava's answer number 2, the general pattern to have grep return only the capture group is:

$ regex="$precedes_regex\K($capture_regex)(?=$follows_regex)"
$ echo $some_string | grep -oP "$regex"

so

# matches and returns b
$ echo "abc" | grep -oP "a\K(b)(?=c)" 
b 
# no match
$ echo "abc" | grep -oP "z\K(b)(?=c)"
# no match
$ echo "abc" | grep -oP "a\K(b)(?=d)"