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.

Output:

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

The output contains

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

With out -n option

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

gitsave.sh:#!/bin/bash

postex.sh:#!/bin/bash

redir.sh:#!/bin/bash

testecho.sh:#!/bin/bash

testreg.sh:#!/bin/bash

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

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

Output:

sanne@192-168-1-103:~/code/sh > grep -l bash *
gitsave.sh
postex.sh
redir.sh
testecho.sh
testreg.sh
whatisshell.sh

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.