Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Use Backreference in Grep

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
like image 792
metdos Avatar asked Jan 11 '12 11:01

metdos


1 Answers

$ 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 
like image 75
kev Avatar answered Sep 21 '22 19:09

kev