Search for a string in multiple files using grep

Today we came across a requirement to check all the files in a directory for a specific entry. The situation is like this. We have two public DNS servers, we usually take backups of zone files when ever we do some changes to zone files. So all the backups are there in one folder. My duty is to check in which file we have a particular change in our second DNS server. Here is the command which we used for grepping all the files at a time, instead of grepping/search file by file.

Search in first level directory

grep -n 'mx' /path/to/your/files/*

-n for numbering the lines in that files which contain mx.


sanne@192-168-1-103:~/code/sh > ls
abc.64001       echooutput.txt       surendra.txt     untitled_folder
abc.txt        test.txt
sanne@192-168-1-103:~/code/sh > grep -n bash *!/bin/bash!/bin/bash!/bin/bash!/bin/bash!/bin/bash!/bin/bash

The output contains

<filename>:<line number>:<line content>

With out -n option

sanne@192-168-1-103:~/code/sh > grep bash *!/bin/bash!/bin/bash!/bin/bash!/bin/bash!/bin/bash

or you can use -l to just list files where they contain mx word.

grep -l 'mx' /path/to/your/files/*


sanne@192-168-1-103:~/code/sh > grep -l bash *

If you want to search within sub-directories as well you can use -r option

grep -rn 'mx' /path/to/your/files/*

Want to master grep then you should visit our grep series.

18+ grep command examples for Linux/Unix

8 Grep command basic Regex examples in Linux/Unix

If you have other than these options share here.

The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.