Search code examples
linuxunixgrepsolarisrm

Rm and Egrep -v combo


I want to remove all the logs except the current log and the log before that. These log files are created after 20 minutes.So the files names are like

abc_23_19_10_3341.log
 abc_23_19_30_3342.log
 abc_23_19_50_3241.log
 abc_23_20_10_3421.log

where 23 is today's date(might include yesterday's date also) 19 is the hour(7 o clock),10,30,50,10 are the minutes.

In this case i want i want to keep abc_23_20_10_3421.log which is the current log(which is currently being writen) and abc_23_19_50_3241.log(the previous one) and remove the rest.

I got it to work by creating a folder,putting the first files in that folder and removing the files and then deleting it.But that's too long...

I also tried this

files_nodelete=`ls -t | head -n 2 | tr '\n' '|'`
rm *.txt | egrep -v "$files_nodelete" 

but it didnt work.But if i put ls instead of rm it works.

I am an amateur in linux.So please suggest a simple idea..or a logic..xargs rm i tried but it didnt work.

Also read about mtime,but seems abit complicated since I am new to linux

Working on a solaris system


Solution

  • Thanks guyz for all the answers. I found my answer

    files=`ls -t *.txt | head -n 2 | tr '\n' '|' | rev |cut -c 2- |rev`
    rm `ls -t | egrep -v "$files"`
    

    Thank you for the help