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 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 *
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 * 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.
If you have other than these options share here.
Latest posts by Surendra Anne (see all)
- Docker: How to copy files to/from docker container - June 30, 2020
- Anisble: ERROR! unexpected parameter type in action:
Fix- June 29, 2020
- FREE: JOIN OUR DEVOPS TELEGRAM GROUPS - August 2, 2019
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018