I need to make it so the files in current directory get amended with a timestamp. It works fine for the first time, but once I run it again it adds another timestamp to the file. I need a way to replace the timestamp, not just add to it.



for file in *
     mv $file "$file""$time"

I'm trying to think of how to overwrite the old files, but because the name changes when it gets amended with the timestamp I can't think of a way.

  • Did you try to debug to see why only works the first time? You have a logic error there that you did not take into account. suggestion: put set -x before IFS and set +x after done. then run the script twice and you will understand why it's adding timestamps. – BitsOfNix Oct 27 '13 at 19:21

You'll need to replace the current portion of the date in the file's name and then replace it. This is a straight string manipulation activity to parse out the base name portion of the file's name. Without more information as to the current naming convention a solution can't really be provided beyond a general approach as to what to do.


Assuming files are named blah_..date..

for file in *

  mv "$file" "$basefile""$time"

This will chop off anything after the _, and store it in $basefile.


$ echo "$file"
blah_Sun Oct 27 15:20:58 EDT 2013

$ echo ${file/_*//}
| improve this answer | |

One way can be to keep the original file names in a file in the same directory and instead of reading the files in a for loop you can use the following while loop to read the file names and add the time stamp to the names:

while read file                                                                                                                                                                    
  mv $file$(date)                                                                                                                                                                  
done < "files.txt"

files.txt can be produced by ls > files.txt for example and you must run this command before running the actual script on the command line or a separate script and just once.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.