3

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.

#!/bin/sh
IFS='
'

time=$(date)

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

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
1

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.

Example

Assuming files are named blah_..date..

for file in *
do

  basefile=${file/_*//}
  mv "$file" "$basefile""$time"
done

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

Names

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

$ echo ${file/_*//}
blah/
0

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

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.