Delete Directories With Find And Exclude Other Directories

Home » CentOS » Delete Directories With Find And Exclude Other Directories
CentOS 7 Comments

Hi all,

I’m attempting to delete some directories and I want to be able to exclude a directory called ‘logs’ from being deleted.

This is my basic find operation (without the exclusion)

# find . -type d |tail -10
./d20160124-1120-df8mfb/deployments
./d20160124-1120-df8mfb/releases
./d20160131-16993-vazqg5
./d20160131-16993-vazqg5/metadata
./d20160131-16993-vazqg5/deployments
./d20160131-16993-vazqg5/releases
./logs
./d20160203-27735-1tqbjh6
./d20160125-1120-1yccr9p
./d20160131-16993-1yf9lnc

I’m just tailing the output so that you have an idea of what’s going on without taking up the whole page. :)

If I try to exlclude the logs directory with the prune command I get back no results.

root@ops-manager:/tmp/tmp# find . -type d -prune -o -name ‘logs’ -print root@ops-manager:/tmp#

What am I doing wrong?

Thanks, Tim

7 thoughts on - Delete Directories With Find And Exclude Other Directories

  • crude thing I would do is:

    find . -type d | grep -v logs

    , but that will also exclude other names containing “logs” it is like:

    Semilogs2
    logs4me

    Thanks. Valeri

    ++++++++++++++++++++++++++++++++++++++++
    Valeri Galtsev Sr System Administrator Department of Astronomy and Astrophysics Kavli Institute for Cosmological Physics University of Chicago Phone: 773-702-4247
    ++++++++++++++++++++++++++++++++++++++++

  • You’re not applying the prune command to items named logs, for one. :)

    find . -name logs -prune -o -type d -print

    find will crawl the directory. Items named logs will not be examined further. Otherwise, if the item is a directory, its name will be printed.

  • That will prune all of the directories whose name is not “logs”, starting with “.”

    So… not terribly useful.

  • Gordon Messmer wrote:

    Right, but a) I think I tried using prune 20 years ago… and b) I thought the o/p wanted to not deal with any directory whose name was logs. leaving off prune would get everything, which is perhaps a bit more useful.

    mark

  • Since you can’t have a file and a directory named “logs” in the same directory at the same time (that I know of), you could turn on bash’s extended globbing.

    $ shopt -s extglob
    $ rm -rf !(logs)

    That will only preserve the top-level entity named logs, though. If there’s a “logs” in a subdirectory, it’ll get deleted.

  • I think you don’t understand. I was pointing out that the command you specified would print the name ‘.’ and that is all. It won’t descend through ‘.’ because you told it to prune all directories not named
    “logs”. That is, I’m trying to point out that it’s your *logic* that’s flawed.

    OP was right in his thinking. The correct way to approach the problem is to ignore (prune) the logs dir, and then to do something with the remaining directories.