8

I have a bunch of files in a folder:

foo_1 
foo_2
foo_3
bar_1
bar_2
buzz_1
...

I want to find all the files that do not start with a given prefix and save the list to a text file. Here is an example for the files that do have a given prefix:

find bar_* > Positives.txt
Jens
  • 65,924
  • 14
  • 115
  • 171
Robert
  • 36,500
  • 34
  • 162
  • 207

6 Answers6

9

If you're doing subdirectories as well:

find . ! -name "bar_*"

Or, equivalently,

find . -not -name "*bar_*"
lurker
  • 55,215
  • 8
  • 64
  • 98
7

This should do the trick in any shell

ls | grep -v '^prefix'

The -v option inverts grep's search logic, making it filter out all matches. Using grep instead of find you can use powerful regular expressions instead of the limited glob patterns.

Jens
  • 65,924
  • 14
  • 115
  • 171
  • Gnu find implements the `-regex` test for "powerful" regular expressions. – rici Jan 26 '14 at 20:44
  • As stated, it inverts the output logic: instead of outputting matching lines, it outputs non-matching lines. – Jens Jan 26 '14 at 20:44
  • ah yes - sorry missed that. – Robert Jan 26 '14 at 20:45
  • @rici Right, but it is best practice in shell programming to avoid GNUisms. In my career they invariably cause portability problems. If I can, I strive to write POSIX compliant scripts. – Jens Jan 26 '14 at 20:48
5

You want to find filenames not starting with bar_*?

recursive:

find ! -name 'bar_*' > Negatives.txt

top directory:

find -maxdepth 1 ! -name 'bar_*' > Negatives.txt
grebneke
  • 4,259
  • 16
  • 24
0

Using bash and wildcards: ls [!bar_]*. There is a caveat: the order of the letters is not important, so rab_something.txt will not be listed.

Benjamin W.
  • 38,596
  • 16
  • 96
  • 104
Etienne
  • 66
  • 4
  • Since you're using Bash, you might as well use extended globs here: `printf '%s\n' !(bar_*) > Positives.txt`. Don't forget to turn extended globs on with `shopt -s extglob` if you use this in scripts. – gniourf_gniourf Oct 03 '16 at 19:15
0

With extended globs:

shopt -s extglob
ls !(bar_*) > filelist.txt

The !(pattern) matches anything but pattern, so !(bar_*) is any filename that does not start with bar_.

Benjamin W.
  • 38,596
  • 16
  • 96
  • 104
0

In my case I had an extra requirement, the files must end with the .py extension. So I use:

find . -name "*.py" | grep -v prefix_

In your case, to just exclude files with prefix_:

find . | grep -v prefix_

Note that this includes all sub-directories. There are many ways to do this, but it can be easy to remember for those already familiar with find and grep -v which excludes results.

Nagev
  • 7,120
  • 2
  • 46
  • 53