I.T. Security and Linux Administration

Aug 27 2010   7:44PM GMT

Using grep…one hell of a tool



Posted by: Eric Hansen
grep, recursive

I’m far from an expert when it comes to grep, or any other CLI tool for that matter, but I did discover one trick with grep that saved me a lot of time.

This command is essentially find, but it builds on it a little bit more by not only displaying the file that the grep’ed text is found in, but also showing you the line of text as well.

grep -H -r  

This does the following:
-H: prints the filename that the text is found in
-r: recursive

This is similar to doing something like:

find . -iname  -exec echo {} \;

I am very horrible at writing advanced find commands, so it’s most likely not very efficient (or working, haha), but you get the idea here I hope.

You don’t have to pipe the data through grep either (i.e.: find … | grep -H -r…) as grep alone can also function as a file/folder locator command. For example, I run the command grep -H -r “H” `pwd` (search for “H” in any files recursively [-H -r] from the current directory [`pwd`]), the output will look something like (for me):

/../.bashrc:HISTCONTROL=$HISTCONTROL${HISTCONTROL+,}ignoredups
/../.bashrc:HISTCONTROL=ignoreboth
/../.bashrc:# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
/../.bashrc:[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"

I “..”‘ed the directories not important (ran it from /home). As you can see, it’s pretty helpful if you want a quick “find in files” creation. I’ve also wrote a bash script to automate this more:

#!/bin/bash

if [ -z "$1" or -z "$2" ]; then
  echo "No parameters passed."
  exit 1
fi

grep -H -r "$1" "$2"

exit 0

Not the most advanced script ever, but it is pretty useful instead of typing grep -H -r … … over and over again.

This is the end of this article, but I would like to say that I’m planning on updating this a lot more now since school is out for a few weeks (yes, I go to college full-time and work full-time…it does leave me with little time to enjoy the finer things in life, but I make do).

Comment on this Post

Leave a comment: