简体   繁体   中英

Delete all except the most recent n files of each prefix (based on file date)?

I'm running this command in my script, and it's deleting all but 5 of each file, but it's not keeping the last 5 files based on date:

ls -rv | awk -F_ '++n[$1]>5' | xargs rm

**underscore is the delimiter between the prefix (hostname) and the filenames.

I've tried some other stuff too, but it didn't seem to do the trick.

I'm running this to delete all but the last n files in a folder and it works correctly:

rm -f $(ls -1t -I "*.sh" | tail -n +21)

This applies to everything though.

I have another folder full of backups from various devices that all have hostname prefixes. The format is: hostname_config.backup-timestamp.

@rici solved it. Dumping the -rv flags and using -t created the behavior I was looking for.

ls -t | awk -F_ '++n[$1]>5' | xargs rm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM