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.
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
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,.
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.