Issue
How to find matching-pattern followed by non-matching-pattern in grep
or egrep
?
Have a file script.txt with entries as below. I would like search for lines matching-pattern followed by non-matching pattern Eg: I would like to get last three lines but not first two.
/script/upgrade/pre_somefile.sql
/script/upgrade/pre_someotherfile.sql
/script/upgrade/anotherfile.sql
/script/upgrade/yetanotherfile.sql
/script/pre_deploy/yetanotherfile.sql
I tried using regular expression similar to below in egrep but no luck.
Tried below in egrep
egrep "/script/(upgrade|pre_deploy)/(?!pre).*" script.txt
If use -v
option then last line is not getting picked.
egrep "/script/(upgrade|pre_deploy)/" script.txt | egrep -v "pre"
Any idea how to implement regex for this case in egrep
Solution
With grep -E/egrep (the same thing), you can do:
grep -E '/script/(upgrade|pre_deploy)/' script.txt |
grep -E -v '/script/(upgrade|pre_deploy)/pre_'
or if your grep has the -P option:
grep -P 'script/(upgrade|pre_deploy)/(?!pre)' script.txt
from the man page:
-P, --perl-regexp
Interpret the pattern as a Perl-compatible regular expression (PCRE).
This is highly experimental and grep -P may warn of
unimplemented features.
But this last one isn't good for production code.
Answered By - Ronaldo Ferreira de Lima Answer Checked By - Cary Denson (WPSolving Admin)