Deleting files using find command

I want to find the files and delete all the files except the last file.
I am using find command , I am sending the find output to a file and getting all the lines except the last one and sending it to the remove command . This is not working. can anyone help me out to do it in the find command itself. Please send me the reply ASAP.

This is one script
#! /bin/ksh
find . -name headdump* >delete.txt
rm -f | cat delete.txt | sed -n '$d; p'

Can I get the result using xargs or exec options in find to get it.The below script will delete all results. Can I filter the output here.

#! /bin/ksh
find . -name heapdump* -exec rm '{}' \; -print >delete.txt

try

find . -name heapdump* -exec rm {} \ ;

this will delete all the files outputted by find command
or

find . -name heapdump*|xargs rm

I want to retain the last file .I should not delete the last file. Please send me the command for leaving the last file found.

do you have command called tac installed??

NO.I guess we dont ve it.

Please clarify what you mean by the "last file". The order of the output from "find" is not much use for operations based on the age of the file.
If you want to retain the most recently created file, "find" is not the right way.

I guess the last file is the recent file only. Could you kindly help me out if i cannot do it using the find command.

One method example assuming files are in current directory.   Obviously adapt to your environment and test before deleting anything.

#!/bin/ksh
# Count files
FILE_COUNT=0
FILE_COUNT=`ls -1tdr heapdump* 2>/dev/null|wc -l`
if [ ${FILE_COUNT} -eq 0 ]
then
        exit
fi
# Calculate how many files to process
FILE_MAX=`expr ${FILE_COUNT} - 1`
#
COUNTER=0
ls -1tdr heapdump*|while read FILENAME
do
        COUNTER=`expr ${COUNTER} + 1`
        if [ ${COUNTER} -le ${FILE_MAX} ]
        then 
                # Process file
                ls -ald "${FILENAME}"
        fi
done

Assuming to be in present working directory,i think this should help you.
it will search for all files name heapdump,sed will remove the last file,and awk will generate the rm command and ultimately piping to shell.

Solution:

find heapdump* |sed '$d'|awk '{print "rm -f "$1}'|sh

Steps:
Created four files heapdump1,heapdump2,heapdump3,heapdump4

robot$:ls -ltr
-rw-r--r-- 1 robot mqm 0 Nov 5 2008 heapdump1
-rw-r--r-- 1 robot mqm 0 Nov 5 2008 heapdump2
-rw-r--r-- 1 robot mqm 0 Nov 5 2008 heapdump3
-rw-r--r-- 1 robot mqm 0 Nov 5 2008 heapdump4

robot$:find heapdump*
heapdump1
heapdump2
heapdump3
heapdump4

robot$:find heapdump* |sed '$d'
heapdump1
heapdump2
heapdump3
(Excluded the last file heapdump4)

robot$:find heapdump* |sed '$d'|awk '{print "rm -f "$1}'
rm -f heapdump1
rm -f heapdump2
rm -f heapdump3

& finally
robot$:find heapdump* |sed '$d'|awk '{print "rm -f "$1}'|sh
will remove all files except heapdump4 !
Hope this is helps :slight_smile: