11

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
Vladimir Panteleev
  • 24,651
  • 6
  • 70
  • 114
metdos
  • 13,411
  • 17
  • 77
  • 120

2 Answers2

19
$ 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 
kev
  • 155,172
  • 47
  • 273
  • 272
-1
grep -E 'CONSTRAINT \`(.*)\` FOREIGN KEY' temp.txt 
Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92