/var/Unix /var/Linux /

This one was given to me by a good friend of mine, and as he says, very often Administrators need to search in textfiles for some specific text or other related information.Here i would like to offer you one of the many many ways to achieve this goal. You want to know?Ok, lets go:

Lets imagine, you (the Admin) need to know i.e. if in one of your scripts you wrote (bash, perl, txt-files or whatever) is a specific pattern or string. The commonly known way would be to manualy open each file and search for it by hand, which probably could take years if you have a lot of them and you wouldnt even notice when you got fired because it took you too long :). Anyway, here we use a easy and fast combination of simple bash syntax and a powerfull tool named “grep”.

# for F in '/my_scripts/*'; do grep -l $F -e
*pattern_you_searching_for* >found_hits.txt; done;

To Explain this a little better take a look on this:

for each file in /my_scripts/
do this {
open the file($F);
search in it for *pattern*
if you found something   {
put the filename into "found_hits.txt"
}   else   {
go on with next file   }
}
i'm done

While bash is going through the directory you passed to the loop it temporarily puts the filename in the variable $F so we have a filename to work with. Then comes “grep -l $F -e ” where -l means (l)ist the file you found, $F means of course the filename we actualy process, and -e means (Regular (e)xpression — The pattern you search for in the file).

Finally comes the output grep produces normally to STDOUT(standard output -> to the console) wich we redirect into a file with “>found_hits.txt” Last we do a “done;” wich tells the computer “end the loop if $F produces a empty return value (a nothing)”.

If we now check the found_hits.txt you have a list of filenames wich have the pattern you searched for inside. Wasn’t this easy ?

TIP: If you i.e. wanna know how often a pattern was found inside the file use “-c” instead of -l to (c)ount the number of found hits in each file.

//Flosse

No Tags
Digg!

Popularity: 4% [?]