Tuesday, November 23, 2010

Recursive grep with filters - command line

Problem:
you have a list o directories that you want to search a pattern BUT you want to exclude a few directories

Solution:
use ls and grep recursive and apply a filter for the directory that you want to exlude


shell$ pwd
/home/
shell$ ls
work documents logs bin
# you want to search on all except logs for pattern 'invoice'

shell$ for i in `ls` ;do  if [ $i != 'logs' ]; then grep -r 'invoice' $i; fi; done
... output


what it happens is this:

the for loop executes based on the command `ls`
all the output is taken and feed it to the do
inside the do we are filtering off 'logs' (with the if) and then search for invoice with grep -r

0 comments: