I am trying to search for a string (e.g. search for string "TODO") in all of my files which are changed locally. That includes files which were already staged and those that are changed but are not added to staging area yet.
4 Answers
Answering my own question. I was able to do it with the following command
git diff --name-only | xargs grep 'My search string goes here'
-
1That doesn't find staged changes, right? For staged and unstaged changes you want
git diff HEAD
– amalloyCommented Apr 15, 2014 at 1:59 -
1This shows the files which are changed and search strings in that files, but what about to search only changes, added, removed strings. ?– FZECommented Feb 19, 2018 at 10:38
-
git diff-index --cached -S{STRINGTOSEARCH} -u HEAD
it requires at least the file added to git viagit add path/to
– FZECommented Feb 19, 2018 at 10:45
The correct answer would be
git diff-index -S{STRINGTOSEARCH} -u HEAD
newly added files have to be added to staging through
git add path/to/filename
searches the intented string in only added/removed strings.
-
kudos for the answer that uses the tool 'as designed' vs introducing outside, cobbled-together approaches– Kay VCommented Oct 6, 2021 at 18:23
I found the -S{STRING}
version rather hard to use since regex are not straight forward. An easier version for me is to pipe the output into grep and use it's pattern matching:
git diff-index --cached -u HEAD | grep -i string
Or for multiple strings at the same time:
git diff-index --cached -u HEAD | grep -i -e string1 -e string2 -e string3
-i
is for case insensitivity and -e
is to add more patterns.
You can add this as an alias to your rc and check for your personal details for every commit if you want.
Here is a bash snippet that works on Debian to accomplish this:
for file in `git status -s -uno`
do
if [[ ! $file =~ [A-Z] ]]; then
echo "$file"
grep -n "TODO" $file
fi
done
Explanation:
git status -s -uno
is short form of git status but excludes untracked files.
The if condition in the for loop skips over the status part of git status -s
to avoid searching through files that don't exist.
Finally the -n option ot grep prints the line numbers. Simply change TODO to whatever you want to find.
I imagine it ought to work on git-bash in windows too...
git grep TODO
? (Note that this starts in working directory, add-- :/
to start at top of repository.) This looks at unmodified files too though.