I am attempting to find files and then grep expression for some string in the files, then only get back the full directory path the files are found in.

find `pwd` -iname '*.py' -type f -exec bash -c "grep -l 'nn'; sed 's[\/](.*)*[\/]/d' {}" \; 

However, the sed expression will have the terminal hang, rather than recursively print out the files and removing the file from the directory path.

I can partially achieve this with:

find `pwd` -iname 'nn*' -type d

However, this expects the directory name to have nn and not for nn inside the file.


1 Answer 1


If you want the path to include the filename:

shopt -s globstar
grep -l 'nn' **/*.py | xargs realpath

To only get the directory the matched file is located in:

shopt -s globstar
grep -l 'nn' **/*.py | xargs realpath | xargs dirname

To remove duplicate directory names:

shopt -s globstar
grep -l 'nn' **/*.py | xargs realpath | xargs dirname | sort -u

If you have very many .py files you may get 'Argument list too long' error.

In that case use find as:

find `pwd` -iname '*.py' | xargs grep -l 'nn' | xargs dirname | sort -u

All the above assumes directories without newlines in the paths. If newlines may be present in the paths, add a comment and I will add some more solutions.

  • So I have a question, when I use: find `pwd` -iname '*.py' -type f -exec bash -c "grep -l 'nn' {}; dirname {}; sort -u {}" \; then final argument sort -u will print out the content also, how would I get it to print out only the unique files with this approach? Jan 10 at 19:37
  • @Workingdollar: I think it should be find `pwd` -iname '*.py' -type f -exec bash -c "grep -l 'nn' {} " \; | xargs dirname | sort -u or find `pwd` -iname '*.py' -type f -exec bash -c "grep -l 'nn' {} | xargs dirname 2> /dev/null" \; | sort -u, i.e. to have the sort after the find command. (it will hang for a bit since sort needs the entire output before printing anyting).
    – user000001
    Jan 10 at 19:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .