Bash command to search for any occurrence of phras

2019-06-07 05:54发布

问题:

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.

回答1:

{ find . -name '*my key phrase*' ;
  grep -rl 'my key phrase' .     ;
} | sort -u > mylist.txt


回答2:

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


回答3:

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 {}))'