Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

How can I rename a file to match the current (rounded) time. If it is for example 10:55 or 11:05 then I would like to rename it to 11.

Something like this:

mv file.txt file_`date +%H`.txt

but with the rounding as described above.

Thanks

share|improve this question

3 Answers 3

up vote 2 down vote accepted

hour=$(date +%H);[[ $(date +%M) -ge 30 ]]&&let hour++;[[ $hour = 24 ]]&&hour=0;hour=$(printf %02d $hour);for f in *.txt;do mv "$f" "${f%.txt}_$hour.txt";done

share|improve this answer
    
printf: `%02': missing format character –  Dado Nov 13 '13 at 23:55
    
@Dado that error means you forgot to specify what format it's looking for, in this case you need a d after the %02... (probably way too late to mention this, but adding it in case anyone finds this via search) –  mason81 Nov 19 at 22:52

You're trying to round the time to the nearest 3600 seconds.

Generally, to round something, add half a unit, then truncate to that unit; this is easy to do using integer division (divide by the unit and discard the remainder, then multiply by the unit - this will always truncate, i.e. round down, but remember that you already added half a unit).

HOUR=$(date -d @$(( ( $(date +%s) + 1800 ) / 3600 * 3600 )) +%H)
mv "file.txt" "file_${HOUR}.txt"
share|improve this answer

On Mac OS X (BSD date):

mv file.txt file_$(date -v +30M +%H).txt

On Linux (GNU date):

mv file.txt file_$(date '+30min' +%H).txt

Both do the same thing: Print the hour value of the current time + 30 minutes.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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