Search Text In Files In Linux

Linux is a very flexible operating system that provides a lot of different actions. Searching text in multiple files in different ways is one of them. There are different commands that can be used to search multiple files in multiple directories.

Search Text In Files

The grep command is the most popular and useful command in order to search text in files. The grep command provides a lot of features and options where search can be done in a single file, multiple files, specific path, or specific file extensions.

grep -rn '/etc/init.d' -e 'kernel'

Search Whole Word In Files

By default provided term is searched in some part of the word. For example the “kernel” term matches “kernel”,”mykernel”,”kernels” etc. But we can specify more strict match which is called word match. The -w option is provided for the whole word match not some part of the word.

grep -rnw '/etc/init.d' -e 'kernel'

CaseInsensitive Search Text In Files

The grep command searches files in a case-sensitive manner. This means upper case and lower case are interpreted as different. The “A” is not equal to the “a” letter. But in some cases, we may need to search in a case insensitive way where “A” is interpreted as “a” too. The -i option is provided to enable case-insensitive text search.

grep -rni '/etc/init.d' -e 'kernel'

Exclude Directories From Search

The text search with the grep command is executed in all files under the specified path. There is no exception excluded from the search. But in some cases, we may want to exclude some directories or files from the text search in Linux. The –exclude-dir option is used to specify the excluded directory names.

grep -r '/etc/init.d' --exclude-dir={test,binary} -e 'kernel'

Exclude Files or File Extensions From Search

Also the files can be excluded from the search according to their names or extensions. The –exclude option is used to specify the file name or the extension by using glob operator. In the following example we exclude the files named “binary” from the search.

grep -r '/etc/init.d' --exclude="binary" -e 'kernel'

In the following example we exclude the files with the “*.bin” extension from the search.

grep -r '/etc/init.d' --exclude="*.bin" -e 'kernel'

Leave a Comment