Linux – How to find files containing text in bash

A few days back, I had to change the timeouts of all the applications on my Linux server.

These applications included nginx, gunicorn, socketio, etc.

One way would be to look for their config files and then search in them.

But I didn’t know where to find all the different configs.

And what if you want to change the timeout value in all files and not just these application configurations? Or maybe you don’t know the server very well \_(-_-)_/

I faced a similar issue. And so I need to find all the files which have the word “keepalive” or “timeout” in them.

A simple way is to open the root path (directory) in an IDE like VSCode and search there.

But of course, I cannot do this in my server!

Also, this will be a good one-time fix. But what if you need to do this again and again – even on your local system?

It would be a lot of work to open these in an IDE and then search for the string in the files.

A simple alternative to this would be to use our terminal!

Finding the text using shell scripts

To fix this, we’ll use the grep command

Run the following command

grep -Rnw "path to look" -e "pattern to search"

A breakdown of the flags is as follows

R: search recursively

n: print line number

w: match the whole word

e: pattern / expression used for search

The output of the above command will include the file in which you found the text, the line number, and the line containing the pattern.

If you only want to search for file names and not see the exact line containing the text, add the l (small L) flag

The command therefore becomes

grep -Rnwl "path to look" -e "pattern to search"

Filtering the search

To filter the scope of our search, we can use –include, –exclude, and –exclude-dir flags

For example,

grep -Rnw "path to look" -e "pattern to search" --include=/home/ubuntu/*

will search only in /home/ubuntu directory and

grep -Rnw "path to look" -e "pattern to search" --exclude=\\*.gitignore

will ignore the occurrences in gitignore files

I hope you found this blog helpful!