linux,

How to search for a string in multiple files on Linux

Sep 19, 2021 · 1 min read · Post a comment

These days there are a lot of code editors which can ease your life in terms of finding some particular string in multiple files or repo. The life will get complicated if you need to SSH into your server through CLI and find a particular string in a bunch of files or directories.

Today, I’ll show you how to search for a string in multiple files on Linux via the grep command.

Prerequisites

  • Linux bash environment
  • sudo privileges

Solution

Step 1. Let’s say if we want to look for a localhost as a keyword into the /var/www/html directory. The following query will get the path, the file name, and print the number line of the exact match:

sudo grep -rnw '/var/www/html/' -e "localhost"

Output:

/var/www/html/tutorial/09/troubleshooting.srt:79: ... `localhost` ...
/var/www/html/tutorial/05/networking.srt:83: ... `localhost` ...
/var/www/html/tutorial/07/access.srt:56: ... `localhost` ...

Step 2. If you need to get only list of the files for that particular keyword, execute:

sudo find /var/www/html/ -type f -exec grep -l 'localhost' {} \;

Output:

/var/www/html/tutorial/09/troubleshooting.srt
/var/www/html/tutorial/05/networking.srt
/var/www/html/tutorial/07/access.srt

Conclusion

Searching for a string in multiple files on a Linux server can be a useful thing if you don’t usually work with code editors. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.