Val Saven
Val Saven

Reputation: 67

Find files which contain string except a couple folders

I'm trying find some files and I've written a bash script for it and use it this way - ./findme.sh "before", but it doesn't work well. What's the problem? How I can rewrite it correctly and more beautify?

#!/bin/bash
string=$1
clear
find . -name "*.*" ! -path "./node_modules" \
       ! -path "./bower_components" \
       ! -path "./public_lib/bootstrap" \
       ! -path "./public_lib/jquery" \
       ! -path "./public_lib/lib/bootstrap" \
       ! -path "./public_lib/lib/jquery" \
-print | xargs grep -o -r -n -C 3 --color=auto "$string" ./

echo "Search end!"
exit 0

Upvotes: 0

Views: 65

Answers (2)

Stefan Hegny
Stefan Hegny

Reputation: 2187

Accoding to the find manpage, you'd have to either specify the full filenames that you want not matched, e.g. ! -path "./node_modules/*" ! -path "./node_modules/*/*" (etc. if it goes deeper) or use prune, e.g. \( \( -path "./node_modules" -prune \) -o ..., in that case you'd have to make a big OR separated with -o for each path to be excluded e.g.

find . -name "*.*" \(  -path "./node_modules"  -prune \) -o \
       \(  -path "./bower_components" -prune \) -o \
       \(  -path "./public_lib/bootstrap" -prune \) -o \
       \(  -path "./public_lib/jquery" -prune \) -o \
       \(  -path "./public_lib/lib/bootstrap" -prune \) -o \
       \(  -path "./public_lib/lib/jquery" -prune \) -o \
-print | xargs...

Edit sorry the condition easily messes up as you see...

Upvotes: 0

Andreas Louv
Andreas Louv

Reputation: 47099

You can properly use grep for this:

#!/bin/bash
grep -rnC 3 --color=auto \
  --exclude-dir={node_modules,bower_components} \
  --exclude-dir=public_lib/{,lib/}{bootstrap,jquery} -- "$1" .

Which will search all files recursive for $1 and show linenumber and three lines above and below the match.

If you want to follow symbolic links you should use -R instead of -r.

--exclude-dir={node_modules,bower_components} uses brace expansions and will expand to:

--exclude-dir=node_modules --exclude-dir=bower_components

And the more advanced --exclude-dir=public_lib/{,lib/}{bootstrap,jquery}, will expand to:

--exclude-dir=public_lib/bootstrap --exclude-dir=public_lib/jquery \
--exclude-dir=public_lib/lib/bootstrap --exclude-dir=public_lib/lib/jquery

Backslash and newline added for clarification.

Upvotes: 1

Related Questions