Mercurial equivalent of git grep
Asked Answered
P

3

14

Is there an equivalent to git grep in Mercurial? That is, search for text only in the working copy, in files tracked by Mercurial. (hg grep searches the repository history.)

Photography answered 12/12, 2014 at 15:1 Comment(3)
grep -r is the closest I know (or similar for ack etc.).Faris
Yeah, unfortunately that includes all the files that aren't tracked by Mercurial (which is what makes git grep convenient).Photography
ack avoids the .hg files but yeah. You could get the list of tracked files from hg and pass those to grep explicitly (assuming you don't have too many).Faris
D
9
hg files "set:grep(regex_goes_here) and not binary()"

See filesets documentation for more information. Briefly, this prints all tracked files which match the given regex and are not binary files (do not contain NUL bytes).

Doretha answered 12/12, 2014 at 15:56 Comment(4)
Does this require a min version of Mercurial, or a specific extension? I couldn't get hg files to work on v2.6.3 (unknown command 'files')Photography
@Matt: shrug it's documented to work, so I'd assume it's in the latest stable version...Doretha
@Matt: I've determined that you can use hg locate in much the same way under older versions of hg.Doretha
Mercurial 3.2 is required. The WhatsNew page says: "files: add new command unifying locate and manifest functionality".Unbend
M
1

Add this alias to ~/.hgrc:

[alias]
grepcwd = ! $HG grep -r 'reverse(::.)' "$1" .

Then use hg grepcwd foobar the same way you would use git grep foobar.

Original source: http://www.emilsit.net/blog/archives/git-is-more-usable-than-mercurial/

Montfort answered 26/4, 2016 at 16:8 Comment(0)
F
1

An upgrade to Kevins answer: Sadly hg files "set:grep(regex_goes_here) and not binary()" does only return the file but does not allow to peak into the found line like git grep does.

So I created an alias. Put the following lines into your ~/.bashrc:

alias hggrep='f(){
  FILES_HG=$(hg files "set:grep(\"$1\") and not binary()")
  for file_grep in $FILES_HG; do
    grep --color -Hn "$1" "$file_grep"
  done
  unset -f f
}
f'

Use like this: hggrep foobar

Feune answered 5/2, 2021 at 14:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.