Hi.
I am trying to automate the movement and renaming of a number of files in a directory. I am using the 'mv' command as I do not have access to 'rename'. I have the following scripted
FILES=$(ls /transfer/move/sys/mail/20130123/)
if [ ! -z "${FILES}" ] ; then
for i in ${FILES} ; do
mv /transfer/move/sys/mail/20130123/${FILES} /transfer/archive/sys/mail/20130123/MYFILENAME_`date +%Y%m%d%M%S00`.dat ; done
fi
which works perfectly when there is only one file in the directory, but when there are multiple files I get the following error
.
I have attempted to add a sleep to the command, but the same error appears.
Can anyone advise what I am doing wrong, or even suggest a better way of achieving this?
Thanks in advance.
You should use $i instead of $FILES on the mv commandline.
If time with seconds is just for unique filenames try mktemp instead:
DIR=/transfer/move/sys/mail/20130123
FILES=$(ls $DIR)
if [ ! -z "${FILES}" ] ; then
for i in ${FILES} ; do
mv -f $DIR/$i $(mktemp --suffix=.dat $DIR/MYFILENAME_XXXXXX)
done
fi
Thanks Chubler_XL.
Unfortunately mktemp does not work and teh following error is returned
I have modified your suggestion to the following
DIR=transfer/move/sys/mail/20130123/
FILES=$(ls $DIR)
if [ ! -z "${FILES}" ] ; then
for i in ${FILES} ; do
mv $DIR/$i /transfer/archive/sys/mail/20130123/MYFILENAME_`date +%Y%m%d%M%S00`.dat
done
fi
but if there is more than 1 file in the source directory, it will only transfer one across and rename it, discarding the remaining files.
Any other ideas?
mktemp is not available on all systems, it's not POSIX.
How about this?
DIR=/transfer/move/sys/mail/20130123
FILES=$(ls $DIR)
if [ ! -z "${FILES}" ] ; then
for i in ${FILES} ; do
F=$DIR/MYFILENAME_$(openssl rand -hex 4).dat
while [ -f $F ]
do
F=$DIR/MYFILENAME_$(openssl rand -hex 4).dat
done
mv $DIR/$i $F
done
fi
Thank you Chubler_XL, that works perfectly!