i want to delete all the files in my directory except the latest one. i need to do this from shell script.
say i have
a.txt - latest file
b.txt,
c.txt..
it should delete all the files except a.txt?
file=$(ls -tr | tail -1)
find . ! -newer "$file" -maxdepth 1 -exec rm {} \;
It's not working sir..Any other option...
modifying vino's script a little
x=`ls -lt | grep ^- | head -1 | awk '{print $NF}'`
find . ! -name . -prune -type f ! -name "$x" -exec rm {} \;
Of course, be sure to backup first before testing
Hi satyajit007,
Put the following 2 lines in your script file and make your script file executable with "chmod +x script_file" and then run your script file.
new_file=`ls -ltr|grep -v drw|tail -1`
find . -type f ! -newer $new_file -maxdepth 1 -exec rm {} \;