1

I have a list of directories where most are in a format like ./[foobar]/. However, some are formatted like ./[foo] bar/.

I would like to use find (or some other utility my shell offers) to find those directories not matching the first pattern (i.e. having text outside the square braces). Until now, I was unable to find a way to "inverse" my pattern.

Any ways to do this?

MechMK1
  • 3,278
  • 7
  • 37
  • 55
  • To clarify - you are looking for a regex that matches a string that has text between `//` characters that is not between `[]` characters? Would that mean any string that doesn't match `/[.*]/` - with appropriate escaping of the `/` and `[]` characters, of course... ? As for "match something that is not"... see http://stackoverflow.com/questions/406230/regular-expression-to-match-string-not-containing-a-word – Floris Mar 06 '13 at 17:14

4 Answers4

3

A simple regular glob will work in this particular example:

$ ls
[a]b [ab]
$ echo \[*\]
[ab]

For more complex patterns you can enable extglob:

!(pattern-list)
     Matches anything except one of the given patterns

(and similar globs)

Or using find:

find dir ! -name ...
Community
  • 1
  • 1
Kevin
  • 53,822
  • 15
  • 101
  • 132
  • Works in general, but piping `find` to `grep` seems easier. – MechMK1 Mar 07 '13 at 11:37
  • As long as you're not going to use it beyond simply looking, that will be fine, though I think the glob is easier (and safer if there are any spaces in file names). – Kevin Mar 07 '13 at 14:45
3

You could combine find with grep and it's -v option. find . -type d | grep -v "[foobar]"

Peter O'Callaghan
  • 6,181
  • 3
  • 26
  • 27
  • Probably the most simple solution. – MechMK1 Mar 07 '13 at 11:35
  • This is incorrect. You need to switch to `grep -Fv` to switch to literal matching, or escape the regex special `\[` because the current regular expression will match any string which contains either `f` or `o` or `b` or `a` or `r` anywhere. – tripleee Feb 21 '18 at 04:59
  • this is not ideal because does not stop `find` from 'finding' the files that do not match. This is a major setback when you are deal with thousands+ files and directories that you want to exclude. – user5359531 May 31 '18 at 19:20
2

find supports negation by means of ! and -not. The latter is not POSIX-compliant. In order to use ! you have to precede it with backslash or put it inside single quotes.

Michał Trybus
  • 11,526
  • 3
  • 30
  • 42
1
find -type d -name '*\]?*'

Unless you insist on opening bracket check...

Wrikken
  • 69,272
  • 8
  • 97
  • 136