I want to delete all log files in some directory, but not the latest 3.
I've done:
DATA_PATH=$(gadmin config get System.DataRoot)
ZK_PATH=${DATA_PATH}/zk/version-2
log_count=$(ls -ltrh ${ZK_PATH} | grep log | wc -l)
limit_files=expr $log_count - 3
echo There is ${log_count} files found in ${ZK_PATH}, ${limit_files} will be deleted, here the list:
ls -ltrh ${ZK_PATH} | grep log | head -${limit_files}
while true; do
read -p "Are you sure to delete these files? " yn
case $yn in
[Yy1]* ) echo execute to delete the files; break;;
[Nn0]* ) exit;;
* ) echo "Please answer y or n.";;
esac
done
How can I delete 9 of 12 files listed?
I thought about printing the list to the files first and then delete it one by one using looping, but I am sure there is code to do it only with one line.
I try to use find ... -delete, -exec, and xargs rm, but I cannot use it properly.
How can I do it?
log_count=…: Why not to parselsoutput (and what to do instead); Grepping forlogis also a bit strange; you could just have done something like${ZK_PATH}/*log*and gotten a list of the files, which is properly countable. – Marcus Müller Mar 20 '23 at 08:17findcommand, so we can't tell you whether you told it to do that. But also, find is not a useful tool here. As Stéphane's answer shows, this can be done through automated filename generation alone (see my first comment!). On its own,findcan't, but you can decorate with time, zero-terminate, sort, de-decorate the things. Again, complicated and not necessary, as Stéphane's answer shows. – Marcus Müller Mar 20 '23 at 08:46