ColinKennedy
ColinKennedy

Reputation: 998

Search only for certain files with grep

I found out today about

git rev-parse --show-toplevel  && git ls-files

Which searches the top directory of a gir repository for all tracked files. Is there a way that I can make grep respect its output and only search through those files?

I tried

git rev-parse --show-toplevel  && git ls-files | grep -r "something" 

but in my small tests showed that it piping wasn't actually working. It would behave the same as just a regular grep command.

I also tried (just as an example)

grep -r "something" --include=`git ls-files`

but I think that only works with single files, since it wasn't showing all possible matches

Upvotes: 0

Views: 91

Answers (1)

Tom Fenech
Tom Fenech

Reputation: 74596

Your first assertion is incorrect, as the two commands are executed separately from one another (the second one only executed if the first one completes successfully).

I guess what you wanted in the first place was:

git ls-files "$(git rev-parse --show-toplevel)"

This passes the top-level directory as an argument to git ls-files.

To grep the list of files for something, you could use xargs:

git ls-files -z "$(git rev-parse --show-toplevel)" | xargs -0 grep 'something'

I've added the -z switch to ls-files and the corresponding -0 switch to xargs, so that both tools work with null-bytes in their input/output, which means that awkward characters in file names don't cause any problems.

I don't think that the -r switch is doing anything useful in grep, since the output of ls-files doesn't contain any directories (git only tracks files).

Upvotes: 1

Related Questions