tags:

views:

209

answers:

3

Linux: I want to list all the files in a directory and within its subdirectories, except some strings. For that, I've been using a combination of find/grep/shell globbing. For instance, I want to list all files except those in the directories

./bin
./lib
./resources

I understand this can be done as shown in this question and this other. But both versions are not solving the case "everything, but this pattern" in general terms.

It seems that it is much easier to use a conditional for filtering the results, but I wonder if there is any compact and elegant way of describing this in regexp or in the shell extended globbing.

Thanks.

+7  A: 

yourcommand | egrep -v "pattern1|pattern2|pattern3"

flybywire
I wasn't aware of this switch of egrep. It is a good way. Thanks!
alvatar
This will suppress all the files which happen to have pattern in their name, which might be more, then you want to suppress.
vartec
I agree with @vartec - this can be dangerous. I prefer the prune option.
Paul Tomblin
It can't be limited with end/begin of line characters? ^ and $ ? Because this option is more compact and easier to read.
alvatar
+6  A: 

Use prune option of find.

find . -path './bin' -prune -o -path './lib' -prune -o -path './resources' -prune -o «rest of your find params»
vartec
+2  A: 

With bash's extglob shopt setting enabled, you can exclude files with ! in your wildcard pattern. Some examples:

  • Everything except bin, lib, and resources

    shopt -s extglob
    ls -Rl !(bin|lib|resources)
    
  • Everything with an i in it, except bin and lib

    ls -Rl !(bin|lib|!(*i*))
    

    (Everything that has an i in it is the same as everything except the things that don't have i's in them.)

Rob Kennedy
The most compact. I've tried similar things, but never realized that if you put the * then anything is matched, so the way was without anything else. I wonder how this could be added to some more restrictions. Like: "everything that has an "i" except "bin" and "lib"...
alvatar