Thursday 8 August 2019

Linux - 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/*

0 comments:

Post a Comment