Renaming the file

Hi guys,

I have written a code to move my file from one directory to another directory, the file is in .csv format and i need to append a current date to the file. the prolem is date is getting appended after the file extension..

here is my code :

cd /data/home/abc/xyz
now=$(date +"%m_%d_%Y")
for file in name.csv
do
    mv "${file}" /data/home/abc/xyz/azher/backup/"${file}_$now"
done

am getting output as name.csv_1_30_2014 but i want to display it as name_1_30_2014.csv

Please help me out..

Thanks in advance.

mv "${file}" /data/home/abc/xyz/azher/backup/"${file%.*}_$now.${file#*.}"
2 Likes

mv $file /data/home/abc/xyz/azher/backup/`echo $file|cut -d. -f1`_$now.csv

1 Like

Remember that if you "name" portion of the filename contain full stops . , then you will have to adjust the suggestion from anbu23 to cater for that.

Perhaps:-

mv "${file}" /data/home/abc/xyz/azher/backup/"${file%.*}_$now.${file##*.}"

The double # will trim off the longest part of the variable it can match, so a filename of abc.def.csv

You also need to consider the path of the source file. If you file variable contains the path, you will have to trim that off too:-

src_dir="${file%/*}"
src_file="${file##*/}"
mv "${file}" "/data/home/abc/xyz/azher/backup/${src_file%.*}_${now}.${src_file##*.}"

I hope that this helps, even if it is unnecessary in your particular case.

Robin
Liverpool/Blackburn
UK

1 Like

thanks guys it worked :slight_smile:

Hi guys am trying to download a file from server, wen i give the file name to download as file.csv , curr date should get appended to that, i tried with the previous code itself but am getting some error in that, am not getting the file extension :frowning:

now=$(date +"%m_%d_%Y")
 --outputFile="/data/home/Script/"${file1%.*}_$now.${file1#*}""

am getting O/P as file_02_05_2014.

i need it as file_02_05_2014.csv, how to achieve this O/P pls guide me through.. :slight_smile: :slight_smile:

This might help you

$ file=sample.csv

$ now=$(date +"%m_%d_%Y")

$ newfile="${file%.*}_$now.${file##*.}"

$ echo $newfile
sample_02_05_2014.csv
1 Like

No Akshay that didnt worked :frowning: i got same output as file_02_05_2014.". :frowning: