Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
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 '14 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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .