hg grep an exact string?

Michael Stassen Michael.Stassen at verizon.net
Tue Jan 3 19:41:27 UTC 2012


On 1/2/12 6:17 PM, wurzel wrote:
> On 2012-01-02 14:18, Ryan Brown wrote:
>>>> Basically trying to find a certain commit matching the string.
>>>>
>>> "^" can be used to anchor your regular expression at the beginning of line,
>>> and "$" at the end, so if you do:
>>> hg grep --all -f '^##.Text$' filename.txt
>>> I think you'll get what you want. (note single-forward-quotes, aka
>>> apostrophe,
>>> around the expression to make sure your shell doesn't try to interpret ^ or
>>> $.)
>> Doesn't seem to work in either standard command Prompt or power shell,
>> hg will search, and come back with no results..
>>
>> hg grep --all -f '^##\.Text$' filename.txt Didn't work either :/
>> _______________________________________________
> Well, I'm stumped. :-) "hg help grep" says it only recognizes Python/Perl
> regexps, but I think ^ and $ work just the same as for regular grep.
>
> Here's a simple test case:
>
> mkdir testgrep
> cd testgrep
> hg init
> echo test > blah
> echo test2 >> blah
> hg add blah
> hg commit -m "null"
>
> echo "Without anchors"
> hg --debug grep --all -f 'test'
>
> echo "With anchors"
> hg --debug grep --all -f '^test$'
>
> Running this gives:
> # ./testgr
> Without anchors
> blah:0:+:test
> blah:0:+:test2
> With anchors
> #
>
> I tried this under Cygwin and also on a Linux machine, same results all places
> so it's not just DOS line endings messing with us or anything. I also tried "hg
> --debug grep --debug --all -f test" but it doesn't give any debug output.
>
> -w

"'^' can be used to anchor your regular expression at the beginning of line, and 
'$' at the end" is a common misconception.  '^' anchors your regular expression 
at the beginning of the *string*, and '$' anchors your regular expression at the 
end of the *string*.  If you read a file line by line, the effect is the same, 
but if you read the entire file into one string, the effect is different.  In 
the latter case, '^' anchors the regular expression at the beginning of the 
*file*, and '$' anchors at the end of the *file*.  It is easy to verify that is 
what is happening here.  Continuing your example:

: hg grep --all -f '^test'
blah:0:+:test

: hg grep --all -f '^test2'

: hg grep --all -f 'test2$'
blah:0:+:test2

It is possible to tell the regular expression engine to treat '^' and '$' as 
line anchors rather than string anchors.  This could be done within hg by 
setting the re.M flag for the search, but hg grep doesn't have an option for 
this.  It can also be done by adding (?m) to the beginning of your regular 
expression:

: hg grep --all -f '(?m)^test$'
blah:0:+:test

: hg grep --all -f '(?m)^test2$'
blah:0:+:test2

Michael



More information about the Mercurial mailing list