Hi All,
I have a requirement where there are 2 files saved on unix directory with names anil_111 and anil_222. I just have to retain the latest file and delete the old file from the directory.
Please help me with the shell script to perform this.
Thanks,
Anil
Try:
ls -1t | sed -n '$p' | xargs rm -i
if [[ anil_111 -nt anil_222 ]]; then
rm anil_222
else
rm anil_111
fi
Hi,
The file does not necesaarily have these names (anil_111 and anil_222). The first name 'anil' would come in parameter and remaining after '_' is timestamp.
I basically have to write a script which will list files starting with 'anil' (as in this case) and remove the older one and retain the latest one.
I hope i made it clear now. Please advice.
Thanks,
Anil
111 and 222 are strange timestamps.
Is your script supposed to determine the age by the timestamps in the files' names, or by the modification timestamps on the files? If the age is determined by the timestamps in the files' names, what is the format of those timestamps?
Hi,
The age of files is determined by the modification timestamps on the files not by timestamp in name. Please help.
Thanks,
Anil
You could try something like:
#!/bin/ksh
IAm=${0##*/}
if [ $# -ne 1 ]
then echo "Usage: $IAm NameBase" >&2
exit 1
fi
set -- "$1"_*
name="$1"
shift
if [ "$name" != "${name%_[*]}" ]
then printf "%s: No files found with names starting with \"%s\"\n" \
"$IAm" "${name%[*]}" >&2
exit 2
fi
if [ $# -eq 0 ]
then printf "%s: Only one file found: \"%s\"\n" "$IAm" "$name" >&2
exit 3
fi
while [ $# -ge 1 ]
do if [ "$name" -nt "$1" ]
then printf "Removing \"%s\"\n" "$1"
echo rm "$1"
else printf "Removing \"%s\"\n" "$name"
echo rm "$name"
name="$1"
fi
shift 1
done
printf "Keeping \"%s\"\n" "$name"
If you try this and it looks like it will do what you want, remove the text in red so it will actually remove files instead of just telling you which files it thinks it should remove.
This assumes that if there are two or more matching files, it should remove all but the latest file.
As ugly as it looks, this might work. The assumption is that the filenames are always the same.
find anil_222 ! -newer anil_111 -exec rm {} \; 2>/dev/null
find anil_111 ! -newer anil_222 -exec rm {} \; 2>/dev/null
The first "find" command will remove "anil_222" if it's not newer than "anil_111". And the second does the opposite check. But only one should ever succeed.