How can I use grep to find a word inside a folder?

前端 未结 14 1711
一个人的身影
一个人的身影 2020-12-02 03:07

In Windows, I would have done a search for finding a word inside a folder. Similarly, I want to know if a specific word occurs inside a directory containing many sub-directo

相关标签:
14条回答
  • 2020-12-02 03:41

    Run(terminal) the following command inside the directory. It will recursively check inside subdirectories too.

    grep -r 'your string goes here' * 
    
    0 讨论(0)
  • 2020-12-02 03:42
    grep -nr string my_directory
    

    Additional notes: this satisfies the syntax grep [options] string filename because in Unix-like systems, a directory is a kind of file (there is a term "regular file" to specifically refer to entities that are called just "files" in Windows).

    grep -nr string reads the content to search from the standard input, that is why it just waits there for input from you, and stops doing so when you press ^C (it would stop on ^D as well, which is the key combination for end-of-file).

    0 讨论(0)
  • 2020-12-02 03:43
    grep -nr search_string search_dir
    

    will do a RECURSIVE (meaning the directory and all it's sub-directories) search for the search_string. (as correctly answered by usta).

    The reason you were not getting any anwers with your friend's suggestion of:

    grep -nr string
    

    is because no directory was specified. If you are in the directory that you want to do the search in, you have to do the following:

    grep -nr string .
    

    It is important to include the '.' character, as this tells grep to search THIS directory.

    0 讨论(0)
  • 2020-12-02 03:49

    GREP: Global Regular Expression Print/Parser/Processor/Program.
    You can use this to search the current directory.
    You can specify -R for "recursive", which means the program searches in all subfolders, and their subfolders, and their subfolder's subfolders, etc.

    grep -R "your word" .
    

    -n will print the line number, where it matched in the file.
    -i will search case-insensitive (capital/non-capital letters).

    grep -inR "your regex pattern" .
    
    0 讨论(0)
  • 2020-12-02 03:50

    Another option that I like to use:

    find folder_name -type f -exec grep your_text  {} \;
    

    -type f returns you only files and not folders

    -exec and {} runs the grep on the files that were found in the search (the exact syntax is "-exec command {}").

    0 讨论(0)
  • 2020-12-02 03:54

    The answer you selected is fine, and it works, but it isn't the correct way to do it, because:

    grep -nr yourString* .
    

    This actually searches the string "yourStrin" and "g" 0 or many times.

    So the proper way to do it is:

    grep -nr \w*yourString\w* .
    

    This command searches the string with any character before and after on the current folder.

    0 讨论(0)
提交回复
热议问题