开发者

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:

Ji开发者_如何学运维ms-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?


#!/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.


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


If you have extglob option enabled:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜