How To Use Backreference in Grep

metdos picture metdos · Jan 11, 2012 · Viewed 8.8k times · Source

I have a regular expression with a backreference. How can use it in a bash script?

Such as I want to print what matches to (.*)

grep -E "CONSTRAINT \`(.*)\` FOREIGN KEY" temp.txt 

If apply it to

CONSTRAINT `fk_dm` FOREIGN KEY

I want to output

fk_dm

Answer

kev picture kev · Jan 11, 2012
$ echo 'CONSTRAINT `helloworld` FOREIGN KEY' | grep -oP '(?<=CONSTRAINT `).*(?=` FOREIGN KEY)'
helloworld

-o, --only-matching       show only the part of a line matching PATTERN
-P, --perl-regexp         PATTERN is a Perl regular expression

(?=pattern)
    is a positive look-ahead assertion
(?!pattern)
    is a negative look-ahead assertion
(?<=pattern)
    is a positive look-behind assertion
(?<!pattern)
    is a negative look-behind assertion