I want to delete all the archivelog, But retain last generated archive log alone.

Currently I am using following which will delete entire/all the archive log and clear the directory itself.

find . -name "dbf*" -mtime +0 -exec rm -rf {} \;

But I want to retain the last generated archive log. How to do? What is the command I need to use for the same?


If you cannot know that only one file per day is generated (your failing command would work in that case), you have to pipe the output of find in which you have a combination of the date-time-stamp of the file and the filename into sort and then exclude the final line with sed before splitting of the date-time-stamp (again with sed) and feeding the resulting names into xargs -0 rm:

find . -type f -name "dbf*" -printf "%T@:%p\0" | sort -z | sed -z '$d' | \
       sed -z 's/[0-9\.]*://' | xargs -0 rm

As the filenames will start with ./ the second sed will only match up to the first ':' even though matching is greedy (-printf "%T@:%p" gives you something like 1424765805.0206990940:./dbf_xyz)

This should work with filenames with spaces and newlines as well, because the whole chain is using NUL terminated "lines"


This works if you don't mind copying the most recent file to another directory while the rest are removed. Assuming you're current working directory is the one with the logs:

cp $(ls -Art | tail -n 1) /tmp \
&& rm -ri /path/to/logs \
&& cp /tmp/$(ls -Art /tmp | tail -n 1) ./ \
&& rm -i /tmp/$(ls -Art /tmp | tail -n 1)

Broken down:

  • cp $(ls -Art | tail -n 1) /tmp copies the output of ls -Art | tail -n 1 which should be the most recently modified file to the /tmp directory. You should probably create a new directory for this, instead of /tmp, or use something that you know won't have any other modified files.

  • rm -ri /path/to/logs should remove all file descriptors in that directory.

  • cp /tmp/$(ls -Art /tmp | tail -n 1) ./ will copy the most recently modified file in /tmp back to your working directory.

  • rm -i /tmp/$(ls -Art /tmp | tail -n 1) removes the file copied to /tmp.

  • 1
    The first bullet item will be fail on filenames that contain newlines. – Anthon Feb 24 '15 at 9:43
  • That's something to consider. It also fails on file names containing a space. The path argument can be wrapped in double quotes cp "$(ls -Art | tail -n 1)" /tmp. I have not tested for newline files. – iyrin Feb 24 '15 at 10:40
  • It doesn't work on files containing new line. – iyrin Feb 24 '15 at 10:44
  • 1
    that is a common problem with parsing output of ls, has been tried to circumvent here and to solve here – Anthon Feb 24 '15 at 11:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.