I have a nested directory structure that looks like this:

└── nested_1
    └── nested_2
        ├── a_file.txt
        ├── b_file.txt
        ├── directory
        ├── other_directory
        ├── y_file.txt
        └── z_file.txt

I want to delete the files inside nested_2 that don't start with A-M, and leave the directories alone. So I want to delete y_file.txt and z_file.txt.

I need to run the find + regex command in top_dir.

I've tried multiple versions of this:

find nested_1/nested_2 -maxdepth 1 -mindepth 1 -type f -regex "nested_1\/nested_2\/.*^[a-m]" #-delete

It doesn't seem to matter what regex I use - the only one that produces any result at all is

find nested_1/nested_2 -maxdepth 1 -mindepth 1 -type f -regex ".*" #-delete

which just gives me a list of all the files in the directory with the leading nested directories (as expected).

Testing it out on regexr hasn't helped either.

What am I missing here?

  1. ^[a-m] should be [^a-m].
  2. After the first letter there may be the rest of the filename, so you need .* after [^a-m], not before.
  3. These backshlashes are not needed (they don't hurt though).

find nested_1/nested_2 -maxdepth 1 -mindepth 1 -type f -regex "nested_1/nested_2/[^a-m].*" #-delete


  • Linux and its filesystems are case sensitive. Things "that don't start with A-M" would be [^A-M].*.
  • Sometimes [^a-m] (or [^A-M]) may not be what you think.
  • Thank you so much! Yes, the lack of closing quote was a typo. Super frustrating to learn that the caret being inside the bracket was the main problem, but hey... that's programming :) – katiekeel Feb 12 '19 at 21:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.