Jim
Jim

Reputation: 851

Bash command to delete all but one file from a directory

I have a backup folder that contains multiple MySQL backups with standard filenames that are derived from the time the backup was taken:

Jims-MBP-2:manual-1 jim$ ls -1
site-name-2011-02-12T19-04-13.mysql
site-name-2011-02-12T19-11-58.mysql
site-name-2011-02-12T19-22-50.mysql
site-name-2011-02-12T19-24-46.mysql
site-name-2011-02-13T14-30-42.mysql

Is there a one-line bash command that will delete all but the most recent backup?

Upvotes: 0

Views: 1749

Answers (3)

Tom Anderson
Tom Anderson

Reputation: 47163

ls | grep -v $(ls -t | head -1) | xargs rm

Better:

ls -rt | tail -n +2 | xargs rm

Armoured against crazy filenames (everything except those with newlines in), suitable for use by paranoids:

ls -rt | tail -n +2 | tr '\n' '\0' | xargs -0 rm

Upvotes: 3

Dennis Williamson
Dennis Williamson

Reputation: 359865

#!/bin/bash
shopt -s extglob
files='sitename*.mysql'
newest=($files)
for f in $files
do
    if [[ "$f" -nt "$newest" ]]
    then
        newest=$f
    fi
done
echo rm !("$newest")

You should avoid parsing ls.

Upvotes: 3

Tomasz Elendt
Tomasz Elendt

Reputation: 1475

If you have extglob option enabled:

rm !(`ls -1 site-name-*.mysql | sort -r | head -1`)

Upvotes: 1

Related Questions