tags:

views:

43

answers:

3

I have a directory where our deployments go. A deployment (which is itself a directory) is named in the format:

<application-name>_<date>

e.g. trader-gui_20091102

There are multiple applications deployed to this same parent directory, so the contents of the parent directory might look something like this:

trader-gui_20091106
trader-gui_20091102
trader-gui_20091010
simulator_20091106
simulator_20091102
simulator_20090910
simulator_20090820

I want to write a bash script to clean out all deployments except for the most current of each application. (The most current denoted by the date in the name of the deployment). So running the bash script on the above parent directory would leave:

trader-gui_20091106
simulator_20091106

Any help would be appreciated.

+1  A: 

A quick one-liner:

ls | sed 's/_[0-9]\{8\}$//' | uniq |
while read name; do
    rm $(ls -r ${name}* | tail -n +2)
done

List the files, chop off an underscore followed by eight digits, only keep unique names. For each name, remove everything but the most recent.

Assumptions:

  • the most recent will be last when sorted alphabetically. If that's not the case, add a sort that does what you want in the pipeline before tail -n +2
  • no other files in this directory. If there are, limit the output of the ls, or pipe it through a grep to select only what you want.
  • no weird characters in the filenames. If there are... instead of directly using the output of the inner ls pipeline, you'd probably want to pipe it into another while loop so you can quote the individual lines, or else capture it in an array so you can use the quoted expansion.
Jefromi
Great work, thanks.
A: 
shopt -s exglob
ls|awk -F"_" '{a[$1]=$NF}END{for(i in a)print i"_"a[i]}'|while read -r F
do 
   rm !($F)
done

since your date in filename is already "sortable" , the awk command finds the latest file of each application. rm (!$F) just means remove those filename that is not latest.

ghostdog74
A: 

You could try find:

# Example: Find and delete all directories in /tmp/ older than 7 days:
find /tmp/ -type d -mtime +7 -exec rm -rf {} \; &>/dev/null
Isabelle