Linux Commnad to Search String in Files

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.

grep in a particular file

If the search string is not present in the file, the output would be blank.

grep not found

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.

grep a string in a file

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

case insensitive grep

If you have spaces in your search string, you have to enclose the string with single or double quotation.

grep with space in search string

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.

grep multiple 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 *

grep in subdirectories

We can see that the above output includes file from different subdirectories.

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

0
0
0
0
0
0