[Solved] How to remove multiple files?

Hi Gurus,

I have below files in one directory. the file name has date and time portion which is exactly the file be created. I need keep only lasted created file which is abc_20140101_1550 and remove rest of the file.

abc_20140101_1300
abc_20140101_1200
abc_20140101_1400
abc_20140101_1500
abc_20140101_1530
abc_20140101_1550

I have tried below code, it works, but looks completed, anybody has some simple way.

#!/bin/ksh
find ./ -name "abc*" |sed 's/\.\///g'> filelist
numfiles=`cat filelist |wc -l`
echo $numfiles
let nfile=$numfiles-1
echo $nfile
tail filelist -$nfile > tailfile
for loop to delete file

Thanks in advance

You can simply use "ls -rt" to get your files sorted by date/time (instead of name) and then remove the last line (the latest file) and delete the others. Use the following blueprint:

ls -rt <optional file mask> |\
sed '$d'|\
while read FILE ; do
     rm -f "$FILE"
done

I hole this helps.

bakunin

2 Likes

I think this code should work, I was unable to find a way to remove last line as you mentioned.

I will try and let you know.

thanks

---------- Post updated at 12:00 PM ---------- Previous update was at 10:59 AM ----------

this code works

1 Like