Sridhar Ratnakumar
Sridhar Ratnakumar

Reputation: 85382

Multiple grep search/ignore patterns

I usually use the following pipeline to grep for a particular search string and yet ignore certain other patterns:

grep -Ri 64 src/install/ | grep -v \.svn | grep -v "file"| grep -v "2\.5" | grep -v "2\.6"

Can this be achieved in a succinct manner? I am using GNU grep 2.5.3.

Upvotes: 20

Views: 41941

Answers (5)

Rob Wells
Rob Wells

Reputation: 37113

Just pipe your unfiltered output into a single instance of grep and use an extended regexp to declare what you want to ignore:

grep -Ri 64 src/install/ | grep -v -E '(\.svn|file|2\.5|2\.6)'

Edit: To search multiple files maybe try

find ./src/install -type f -print |\
    grep -v -E '(\.svn|file|2\.5|2\.6)' | xargs grep -i 64

Edit: Ooh. I forgot to add the simple trick to stop a cringeable use of multiple grep instances, namely

ps -ef | grep something | grep -v grep

Replacing that with

ps -ef | grep "[s]omething"

removes the need of the second grep.

Upvotes: 26

The following script will remove all files except a list of files:

echo cleanup_all $@


if [[ $# -eq 0 ]]; then
FILES=`find . -type f`
else
EXCLUDE_FILES_EXP="("
for EXCLUDED_FILE in $@
do
    EXCLUDE_FILES_EXP="$EXCLUDE_FILES_EXP./$EXCLUDED_FILE|"
done
# strip last char
EXCLUDE_FILES_EXP="${EXCLUDE_FILES_EXP%?}"
EXCLUDE_FILES_EXP="$EXCLUDE_FILES_EXP)"
echo exluded files expression :  $EXCLUDE_FILES_EXP

     FILES=`find . -type f | egrep -v $EXCLUDE_FILES_EXP`
fi

echo removing $FILES

for FILE in $FILES
do
    echo "cleanup: removing file $FILE"
    rm $FILE
done   

Upvotes: 0

Flimm
Flimm

Reputation: 150793

Use the -e option to specify multiple patterns:

grep -Ri 64 src/install/ | grep -v -e '\.svn' -e file -e '2\.5' -e '2\.6'

You might also be interested in the -F flag, which indicates that patterns are fixed strings instead of regular expressions. Now you don't have to escape the dot:

grep -Ri 64 src/install/ | grep -vF -e .svn -e file -e 2.5 -e 2.6

I noticed you were grepping out ".svn". You probably want to skip any directories named ".svn" in your initial recursive grep. If I were you, I would do this instead:

grep -Ri 64 src/install/ --exclude-dir .svn | grep -vF -e file -e 2.5 -e 2.6

Upvotes: 8

ghostdog74
ghostdog74

Reputation: 342443

you can use awk instead of grep

awk '/64/&&!/(\.svn|file|2\.[56])/' file

Upvotes: 2

Chmouel Boudjnah
Chmouel Boudjnah

Reputation: 2559

You maybe want to use ack-grep which allow to exclude with perl regexp as well and avoid all the VC directories, great for grepping source code.

Upvotes: 1

Related Questions