Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Anyone have bash script to delete all be x number of files?

Status
Not open for further replies.

BobMCT

IS-IT--Management
Sep 11, 2000
756
0
0
US
I've done this in a multitude of ways in years past but not wanting to reinvent the wheel (so to speak) I am hoping that some readers here may have a script they would be willing to share.

My task is - given a partial name of a file, delete the last n occurences.

Example: ls -lt abc123* |wc -l yields say 10 files. I'd like to delete all above the count of a value such as 5 or 6.

Anyone know how to accomplish this without shell arithmetic or storing results in temp files?

I am quite curious to see how others may approach this.

Thanks for any scripts and/or snippets.

Bob [bigears]
 
Hey try something like this:

rm -f $(ls ABC* | head -n 10)

This will remove all files that are returned by the command ls ABC* | head -n 10

ls ABC* will return all files that begin with the string ABC then pipe it to head -n 10 where 10 is the number of files you want to remove.

Hope this helps.
 
Thanks JohnnyAsterisk,

I did get that far but my question was really asking how to remove the last x files (but can't use tail because we don't know how many files there are and I want to keep the most recent x).

B
 
Let's say you want to keep the 10 most recent files:

Code:
ls -t | tail +11 | xargs rm -f
# or, using johnny's syntax
rm -f $(ls -t | tail +11)

The ls -t is assuming the last modification times are what you want to base the "keeping" upon.

Annihilannic.
 
Thanks Annihilannic!

I completely missed the "+" modifier during my original research & testing. Works great WITHOUT the arithmetic now.

B [thumbsup]
 
Find has an option to search for files older/newer than X days,hours,...

Code:
find ABC* -mtime +3 -exec rm {} \;
Removes the ABC* files older than 3 days.
 
Aware, FedoEx;

The the task was to retain the most recent "n" number of similar files no matter how old they might be. The "+" modifier on tail works like a charm.

Thanks for responding anyway.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top