如何在Bash中使用反向引用

时间:2012-01-11 11:50:26

标签: regex bash unix text-processing

我有一个带有反向引用的正则表达式。如何在bash脚本中使用它?

例如我想打印匹配到(。*)

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

如果将其应用于

CONSTRAINT `fk_dm` FOREIGN KEY

我想输出

fk_dm

2 个答案:

答案 0 :(得分:13)

$ 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 

答案 1 :(得分:-2)

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