Home > OS >  Find Path to Files containing specific word - How can I know which file in a directory contain the s
Find Path to Files containing specific word - How can I know which file in a directory contain the s

Time:07-03

I manage to find the word that I desire with the following command in a github repository

git log --all -p | grep 'abc'

abc is a word located in a specific file.

My question is how can I find the file path to the string that I desire? How can I know which file contain the word that I want which is abc ?

For example, doing the above command would get me

(this.b(),this.abc);

but I would like to know which exact folder and which exact file is this piece of string/code coming from.

Any suggestion is appreciated.

CodePudding user response:

Just run

git log --all -p

This shows the output in the pager, usually less. You can search, scroll forward and backward.

To search the string, type / a b c Enter (the abc here is a regular expression, not a literal string). Type n to find the next occurrence. When you have found one, you can scroll back with b and look at the patch text to see which file it is. (BTW, type Space to scroll forward; type q to exit the pager.)

CodePudding user response:

The following (tested with GNU awk) should be an approximation of what you want:

git log --all -p |
awk '/^diff --git / {files = $0}
     /^@@ /,/^(commit |diff --git )/ {if(index($0, "abc")) print files}'

We store the diff --git line in variable files. Then, if your string is found between the following line starting with @@ and the line starting with commit or diff --git , the files variable is printed.

It is an approximation only because string abc could also be found in the diff --git or commit lines and also because ^@@ , ^diff --git or ^commit could be found in file contents.

More accurate solutions exist but they are more complicated and those I can think of cannot be 100% perfect.

CodePudding user response:

git grep -l 'abc'

Option -l list file names where the pattern is found in the current (HEAD) commit.

  • Related