Adding date and time to file name

Hi All,

i wanted to add date and time to the file names in the same directory so lets say a file in the directory is test.txt then after running the shell script it should be test-15-11-2010.txt.

So I used the following script which works,

#!/bin/bash

thetime=`date +%Y-%m-%d--%H:%M:%S` #
for i in *.txt
do 
      mv $i ${i%.txt}$(date "+_%Y%m%d.txt")
done

But it does work only for .txt files I want to modify it so that it can take any file extension.

Thank you.

You could use (assuming this shell script is at the path where you need to add the date and time )

for i in *

or to be more precise

for i in *.*

As the former one would change the name of the sub-directory if its present in the current working dir.

yea thankx for reply.. but yea that i could figure out but the main part is.

mv $i ${i%.txt}$(date "+_%Y%m%d.txt")"

here i have hard coded .txt.. that is what i want to change..

Store the file's extension in a variable before mv command and substitute in the variable later while using mv command.

#!/bin/bash

thetime=`date +%Y-%m-%d--%H:%M:%S` #
for i in *.*
do 
	extn=${i##*.} # save the extension of the file
	mv $i ${i%.*}$(date "+_%Y%m%d.${extn}")
done
1 Like

awesome! thankx mate! it did work!

Sorry I am a beginner in shell. I wanted to handle files without extension as well... as of now it works for text.txt or anything which has file extension but if some file name is just "debug" it wont work for that.. So i tried to write another for loop with just * instead of*.* but ofcourse it dint work.. any ideas how should i proceed.
thank you,.

Why store it? (but it's preferable to store the date string to avoid calls to date in the iteration.

#!/bin/bash
D=$(date +%d-%m-%Y)
for F in *.*
do 
	mv $F ${F%.*}-$D.${F##*.}"
done
1 Like

how about for files without any extension.. like lets say just "debug" and not "debug.txt" ? any idea?

Something like
#!/bin/bash
D=$(date +%d-%m-%Y)
for F in *
do
Dot="${F//[^\.]/}" # this removes anything but a dot
if [ -n "$Dot" ]; then
mv "$F" "${F%.*}-$D.${F##*.}"
else
mv "$F" "$F-$D"
fi
done

Note: I put quotes around filenames to avoid problems with spaces in them.