D&C GLug - Home Page

[ Date Index ] [ Thread Index ] [ <= Previous by date / thread ] [ Next by date / thread => ]

Re: [LUG] Find (and remove) empty directories

 

On Wed, 20 Apr 2011, Henry Bremridge wrote:

I seem to recall there was a series of discussions on using Find to
discover (and delete) empty directories. From memory there was a one line
command that would do it.

   Using tar to back up new files from a certain date from the wife's
   hard-drive. I now have to unpack the tar file and delete empty
   directories.

Out of curiosity, why bother deleting them?

I tried searching this morning but could not find any.

Before I started experimenting Google has the following commands

   find -depth -type d -empty -exec rmdir {} \;
   find -type d -empty -delete

   http://duramecho.com/ComputerPrograms/DeleteEmptyDirectories/index.html

Any help much appreciated

The above mentioned commands seem to work for me, so what's up?

Find is great, although in this instance you probably don't need -depth, as you can't go deeper than an empty directory, so:

  find . -type d -empty -print

Remember that find's predicates are assumed to be concatenated with 'and' unless you use -o (for 'or')

So that reads as:

  find from the current directly ('.'),
    type d (directory)
    and
    empty
    and
    print

You can use -ls rather then print if you like.

Once happy with that, then you can add on the -exec rmdir {} \;


If you're currently doing this and it's not deleting the empty directorys, then is it possible that the directorys are not really empty, but full of 'dot' files? These would normally be hidden from view, but the -empty predicate would fail...

e.g. a test I've just setup:

  $ mkdir test
  $ ls -laR > test/.dotfile
  $ find . -depth -type d -empty -print

Returns nothing, but:

  $ ls -la test
  total 20
  drwxrwsr-x  2 gordon gordon  4096 Apr 20 17:48 .
  drwx--S--- 17 gordon gordon 12288 Apr 20 17:48 ..
  -rw-rw-r--  1 gordon gordon   164 Apr 20 17:48 .dotfile

If so, then try this: (crude, but sort of works)

  ls -laR | grep ' \.[a-z|A-Z]'

That will recursively list files that start with a dot then a-z|A-Z but it won't tell you what directory they're in.. If there's only a few, then you can try this:

  ls -laR | less

and use the knowledge that less uses regular expression matching - so type

  / \.[a-z|A-Z]

(that's forward slash space backslash dot, etc.)

Then you can use the up & down arrow keys in less to look near the identified filename, and the 'n' key to search for the next one...

This might be a bit tedious if you have lots though.

Gordon

--
The Mailing List for the Devon & Cornwall LUG
http://mailman.dclug.org.uk/listinfo/list
FAQ: http://www.dcglug.org.uk/listfaq