How to add the dat time stamp just before the last extension of a file?

hi,

A file name is in the form inside a variable

FILE_NAME="s1.txt.xls"

i want to append date and time stamp inbetween s1.txt and .xls. so after appending date time stamp the file name would be

MOD_FILE_NAME="s1.txt.201307251422.xls"

currently i am using the below code

FILE_NAME="s1.txt.xls"
MOD_FILE_NAME=`echo $FILE_NAME | cut -d"." -f 1-2`
MOD_FILE_NAME=$MOD_FILE_NAME.`date +%Y%m%d%H%M%S%N`.xls

the above code will not work if there are more than 2 dots in between the file name.
i always want to insert the date time stamp just before the final extension of the file. how can i do?

$ echo ${FILE_NAME%.*}.DATE_GOES_HERE.${FILE_NAME##*.}
s1.txt.DATE_GOES_HERE.xls

$ FILE_NAME=1.2.3.4.5.6.7
$ echo ${FILE_NAME%.*}.DATE_GOES_HERE.${FILE_NAME##*.}
1.2.3.4.5.6.DATE_GOES_HERE.7
echo ${FILE_NAME%.*}.$(date +%Y%m%d%H%M%S%N).${FILE_NAME##*.}

Thanks for the solution. i want to store the filename with date time stamp in a variable. how can i do that??

FILE_NAME="s1.txt.xls.gk"
MOD_FILE_NAME=`echo ${FILE_NAME%.*}.``date +%Y%m%d%H%M%S%N``.${FILE_NAME##*.}`
echo "FILE_NAME = {$FILE_NAME}"
echo "MOD_FILE_NAME = {$MOD_FILE_NAME}"

the output of the above script is

$ sh datetime.sh
datetime.sh: line 2: .gk: command not found
FILE_NAME = {s1.txt.xls.gk}
MOD_FILE_NAME = {s1.txt.xls.20130725030022368251000}

its not adding the last extension to the modifies file name and also gives an error on line 2. can you tell me how can i store the new file name in a variable please??

You've gone overkill on the backquotes.

The $(...) method of command substitution is easier on the eyes, and replaces the 'obsolete' `...` method.

$ MOD_FILE_NAME="${FILE_NAME%.*}.$(date +%Y%m%d%H%M%S%N).${FILE_NAME##*.}"
$ echo "$MOD_FILE_NAME"
s1.txt.xls.20130725120827N.gk
2 Likes