LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Delete all .log files and .bat files except the most recent? (https://www.linuxquestions.org/questions/linux-newbie-8/delete-all-log-files-and-bat-files-except-the-most-recent-918876/)

alancampbell6 12-15-2011 08:18 AM

Delete all .log files and .bat files except the most recent?
 
I have a directory with multiple .log files and multiple .bat files.

1. I want to delete all .log files.

2 I want to delete all .bat files except the most recently created one.


Any ideas on how i could do this?

thesnow 12-15-2011 08:52 AM

You haven't mentioned whether you need to do this on a repeated basis (script), so this assumes you don't. Also assumes you are in the directory containing the files.

1. rm *.log

2a.
Code:

ls -latr *.bat
2b. This will give a list of all bat files, most recent is listed last
2c.
Code:

for i in `find ./*.bat | grep -v "whatever bat file you want to keep"`; do rm $i; done
Or, you could just temporarily rename/move the one bat file you want to keep, delete the remaining ones, and move it back. Before I run something like 2c I usually put "echo" or "ls" in place of "rm" to see that it's giving me what I expect. Then, once absolutely sure it's right, run it with the "rm" (since once you hit Enter on the rm there's no going back).

catkin 12-15-2011 09:11 AM

Is this a homework question?

EDIT:

Never mind, an answer has already been given.

An alternative for the .bat files:
Code:

echo rm "$( /bin/ls -1t *.bat | head -n-1 )"
Notes:
  1. That's a number 1 in ls -1t, not a letter l.
  2. When you are confident it is generating the correct rm command, remove the echo.

Cedrik 12-15-2011 09:17 AM

Or there is always logrotate to manage log files

Code:

man logrotate


All times are GMT -5. The time now is 05:39 AM.