Tuesday, March 6, 2012

WordFinder script: The script that crawls thru' every files to find what you are looking for

Have you ever wanted to find the 'word' in files located under directory containing sub-directories and tons of files. It would be nightmare to search in individual file. You can make your life easy by writing a script that crawls thru' every files under that directory and return the file name along with the line that contains the word you are looking for.

Ok let's get started with BASH script that will do the job for us.

$vim WordFinder.sh
#!/bin/bash
#Author: erdevendra@gmail.com
#
#Usage: This scripts finds a word in each and every files located under the specified location

#
#Syntax:
# .\WordFinder.sh
#

for x in `find $1 -type f`
do
#find files under the specified location and use for loop to go thru each files
         grep -i $2 $x
#search for the pattern in the file
          if [ $? -eq 0 ]
#Check if grep cmd executed successfully
             then echo $x
#if grep cmd executed successfully (i.e if pattern found) display the file name
          fi
#end IF loop
done
#end FOR loop


Give an executable permission to the file

#chmod 777 WordFinder.sh

(Note: 777 gives full permission to everyone in the system)

You are good to go. Now you just need to run that script to find what you are looking for.

Example:
#WordFinder.sh  <location>  <word_you_are_looking_for>

Let's say I want to find word 'listen' in '/etc' directory, I can run following command:
#WordFinder.sh  /etc  listen

No comments:

Post a Comment