Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between grep and perl regex?

Tags:

regex

grep

perl

I have a problem with what I think is a difference in grep's regex and perl's regex. Consider the following little test:

$ cat testfile.txt 
A line of text
SOME_RULE = $(BIN)
Another line of text

$ grep "SOME_RULE\s*=\s*\$(BIN)" testfile.txt 
SOME_RULE = $(BIN)

$ perl -p -e "s/SOME_RULE\s*=\s*\$(BIN)/Hello/g" testfile.txt
A line of text
SOME_RULE = $(BIN)
Another line of text

As you can see, using the regex "SOME_RULE\s*=\s*$(BIN)", grep could find the match, but perl was unable to update the file using the same expression. How should I solve this problem?

like image 926
Eric Lilja Avatar asked Oct 18 '11 10:10

Eric Lilja


People also ask

Is grep the same as regex?

grep is one of the most useful and powerful commands in Linux for text processing. grep searches one or more input files for lines that match a regular expression and writes each matching line to standard output.

Is Perl faster than grep?

perl is faster than all but egrep , but even sed edges your basic grep by a hair.

What is in Perl regex?

Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“.


1 Answers

Perl wants the '(' and ')' to be escaped. Also, the shell eats the '\' on the '$', so you need:

$ perl -p -e "s/SOME_RULE\s*=\s*\\$\(BIN\)/Hello/g" testfile.txt

(or use single quotes--which is highly advisable in any case.)

like image 94
William Pursell Avatar answered Nov 06 '22 05:11

William Pursell