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.
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.
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.