How to add a datetime stamp at a particular position in a filename?

hi,

i have some files in a directory say

abc.txt
def.txt
ghi.txt

i am storing these file names in a temp file.

ls -l | grep "^-" | awk '{print $NF}' > temp_file$$

i want to add a date time stamp at a particular place in the file names.
it can be
1) before the extension
filename_dateTime.extn ( abc_datetime.txt )
2) after the extension
filename.extn_datetime ( abc.txt_datetime )

there is a variable which contains the place where the date time stamp needs to be added.

stamp_pos which can contain two possible values

filename_DT.extn 
filename.extn_DT

i want to parse this string "filename_DT.extn" , and depending on the place where the substring "DT" occurs, i need to add the datetime stamp.

initially i thought, i will 1st read each file name from the temp file(containing list of files in the directory) and also parse the variable stamp_pos and accordingly add substring "DT" to the original file names
suppose,

stamp_pos="filename_DT.extn"

then the DT will be added as

abc_DT.txt
def_DT.txt
ghi_DT.txt

in the next step i thought i will parse the each original file name and replace DT with the date time stamp.

do anyone has an idea how to do this?

At some point a toggle must be switched for prefix or suffix.

Let's use a command line argument:
e.i stamp_it 0

for f in *.txt; do
    case ${1} in
    0)
    echo $(date "+%F").${f} ;;
    1)
    echo ${f}.$(date "+%F") ;;
    *)
    echo ${f} ;;
    esac
done

Why not to solve it as a boolean?

If "prefix" is not an argument at command line do "suffix" . You get the idea.

for f in *.txt; do
    [[ ${1} = "prefix" ]] && echo $(date "+%F").${f} || echo ${f}.$(date "+%F")
done
1 Like

Try this and adapt to your needs:

stamp_pos=filename.extn_DT
[ "${stamp_pos#*_DT}" ]; EC=$?; read DT$EC DT$((1-EC)) <<< "_2013/11/16 "
while IFS=. read FN EXT; do echo $FN$DT0.$EXT$DT1; done <file
1 Like