I'm looking for a simple bash command to search for a phrase in filenames, directory names, and within text of all files. It should return a list of files and directories. Ideally, I'd like the option to pipe it to a file like > myfiles.txt
Something like:
find 'my key phrase'
find 'my key phrase' > mylist.txt
would return:
/home/stuff/filewithmykeyphraseinit.txt
/home/stuff/a filename with my key phrase.doc
/home/stuff/a directory with my key phrase/another subdirectory/
EDIT: I'm getting a lot of great suggestions I'm currently testing. One issue: is there a way to make these case-insensitive? I believe adding -i to grep works. How about find for filepaths/names? Also, I'd like to have the option to either send the output to a text file or to screen.
{ find . -name '*my key phrase*' ;
grep -rl 'my key phrase' . ;
} | sort -u > mylist.txt
You're almost there, just specify you want to match file names and add wildcards to your pattern:
find -name '*my key phrase*' > mylist.txt
To search within the contents of files, use the grep command (with -r recursive option, or rgrep):
rgrep -l 'my key phrase' >> mylist.txt
one command to do it all (using xargs and bash)
find | xargs -I {} bash -c '(([[ -f "{}" ]] && grep -l "my key phrase" "{}") || ([[ "{}" =~ "my key phrase" ]] && echo {}))'
来源:https://stackoverflow.com/questions/12865138/bash-command-to-search-for-any-occurrence-of-phrase-and-return-list-of-files-and