For developers, searching a string (text) in files is a everyday requirement. If you are using the Linux graphical user interfaces like GNOME ot KDE etc, then it is very easy and intutive. But Linux users use the commnad line interface (CLI) quite often. We’ll see how to use grep (Global Regular Expression Print) command to search a string in the files of a directory including subdirectories.
Search in a Particular File
Here is the command to check whether ‘Linux’ is present in a file ‘aio.c’.
# grep Linux aio.c
Here is the output of this command.
If the search string is not present in the file, the output would be blank.
The grep command is case sensitive by default. The above result shows only the ocurrences of ‘Linux‘ but not ‘linux‘. If you search for ‘linux‘ instead of ‘Linux‘, you’ll get different result.
If you want to search in a case insensitive way, i.e., want to get the occurences of both ‘Linux‘ and ‘linux‘, you have to use -i (ignore case) option.
# grep -i linux aio.c
If you have spaces in your search string, you have to enclose the string with single or double quotation.
Search a String in Multiple Files
If you want to seach a string in multiple files, you have to specifiy the file names at the end of the command. The file names should be separated by space. In the example below, we searched ‘Linux‘ in three files.
If you want to seach the string in all file in the current directory, then you have to specify ‘*’ in place of file name.
# grep Linux *
The output will show all the files where the string, ‘Linux‘, exists.
You can also specify the file types also. For example if you want to search ‘Linux‘ in ‘.c‘ files only, then you have to specify ‘*.c‘ in place of file name.
# grep Linux *.c
If you wan to search in the files that start with a, then you have to specify ‘a*’ in place of file name.
# grep Linux a*
Search in Subdirectories
In all examples above, search is limited to the current directory. If you want to search in subdirectories, then you have to use the ‘-r‘ (recursive) option. Here is the command if you want to search ‘Linux‘ in subdirectories also.
# grep -r Linux *
We can see that the above output includes file from different subdirectories.