Bash command to search for any occurrence of phrase and return list of files and paths

纵然是瞬间 提交于 2019-12-08 06:32:15

问题


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


来源:https://stackoverflow.com/questions/12865138/bash-command-to-search-for-any-occurrence-of-phrase-and-return-list-of-files-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!