Bash command to search for any occurrence of phras

2019-06-07 05:43发布

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.

3条回答
该账号已被封号
2楼-- · 2019-06-07 06:19

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楼-- · 2019-06-07 06:29
{ find . -name '*my key phrase*' ;
  grep -rl 'my key phrase' .     ;
} | sort -u > mylist.txt
查看更多
Summer. ? 凉城
4楼-- · 2019-06-07 06:35

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 {}))'
查看更多
登录 后发表回答