PDA

View Full Version : script to delete empty files and folders




appatight
Aug 22, 2013, 03:01 PM
First off I just want everyone to know that I absolutely suck at programming. I know some UNIX commands and such but when it comes to scripting I will clearly get lost. I have an external HDD that has a lot of files and empty folders. I would like a script that will delete any files that is 0kb and also any empty folders. Can one of you scripting gurus be of any help? All help would be appreciated.



aaronvan
Aug 22, 2013, 03:38 PM
I know some UNIX commands...

That puts you in the 1% of computer users.

Your task seems fairly trivial. Have you tried it in Automator?

pitaya
Aug 23, 2013, 09:52 AM
Be careful with find commands of this nature:

$ man find | grep empty
-empty True if the current file or directory is empty.
$ mkdir -p Temp/{Empty,NotEmpty}
$ man find > Temp/NotEmpty.txt
$ touch Temp/Empty.txt
$ touch Temp/NotEmpty/Empty.txt

$ find Temp
Temp
Temp/Empty
Temp/Empty.txt
Temp/NotEmpty
Temp/NotEmpty/Empty.txt
Temp/NotEmpty.txt

$ find Temp -empty
Temp/Empty
Temp/Empty.txt
Temp/NotEmpty/Empty.txt
$ find Temp -empty -delete
$ find Temp
Temp
Temp/NotEmpty.txt

$ mkdir -p Temp/{Empty,NotEmpty}
$ touch Temp/NotEmpty/Empty.txt
$ man find > Temp/NotEmpty/NotEmpty.txt

$ find Temp -empty
Temp/Empty
Temp/NotEmpty/Empty.txt

$ find Temp -empty -delete
$ find Temp
Temp
Temp/NotEmpty
Temp/NotEmpty/NotEmpty.txt
Temp/NotEmpty.txt
$

subsonix
Aug 24, 2013, 06:24 AM
You can try something like this. Keep in mind that it can potentially cause a lot of damage if it's done on an entire directory, and even more so if it's done on all sub directories. I commented out the rm command here so that you can test it first, use at your own risk etc. :D


#!/bin/bash

function delete_if_empty {
if [[ $(file -b "$1") == "empty" ]]
then
#rm "$1"
printf "%-25s is an empty file\n" "$1"
fi

if [[ $(file -b "$1") == "directory" ]]
then
if [[ -z $(ls -A "$1") ]]
then
#rm -d "$1"
printf "%-25s is an empty directory\n" "$1"
fi
fi
}

for i in * ; do
delete_if_empty "$i"
done


This script applies the delete_if_empty function on the current directory, if you wish to include all sub directories you can replace the * in the loop with $(ls -R).

jaduff46
Aug 24, 2013, 12:04 PM
You need to be really careful with this. Whatever you do try it on a small directory, then one with a subdirectory, then one with multiple subdirectories.

The reason for my caution is that I had a consultant who tried something similar a few years back on a multi-user (50+) Unix box (looking for files with zero length) and came close to cutting off the machine from the outside world. Turns out all the lines coming into /dev/tty (the outside lines into the machine) had zero length.

peoplevoice
Aug 24, 2013, 12:08 PM
find /Volumes/ExternalHardDiskDriveName -empty -exec rm {} 2>/dev/null \;

Replace ExternalHardDiskDriveName for the real name of the HDD.

This name is being displayed in the Finder Window.