Set custom time and increment by a second, per file in a directory using BASH

Viewed 135

I want to set the time of each file in a directory to start at the zero hour of the day in question, and just add a second to each file recursively (incrementing each time)

So, grabbing today's date and time 2020-06-07 03:28:00 I want to reset the time of the files, in the order of their name, to start at 2020-06-07 00:00:00, and then add a second to each file, incrementing each time. I kinda know what I need to do, but don't know how to do it, as I'm not proficient enough in bash.

  1. I assume a for loop to go through the files by name, and to increment each file one above the previous
  2. I know I need to set the time to current date, then reset the time to 00:00:00
  3. I assume touch -d with a "+1 second" is the right option
  4. I don't need to change the filename, just the timestamp

I just have no idea how to write the code.

The output would (effectively) be for all files in:

dir
 - file1.txt 2020-06-07 03:29:22
 - file2.txt 2020-06-07 03:27:34 
 - file3.txt 2020-06-07 03:28:03
 - etc

change to:

dir
 - file1.txt 2020-06-07 00:00:00
 - file2.txt 2020-06-07 00:00:01
 - file3.txt 2020-06-07 00:00:02
 - etc

I'm using PodcastGenerator, and noticed that the software uses the file's timestamp to create the publish date/time. This is a quick hack to solve the problem instead of having to hack the rss.xml file each time. I don't care about the actual date/time of the files in the long run, just being able to order them properly in the Podcast software.

On that note, if there are any easier ways of creating rss feeds from a bunch of files for a podcast I'm happy to accept suggestions. I've researched a few and this seems to be easiest solution right now.

1 Answers

You can work with dates using the date command, and then set the time using the touch command.

today=`date +%F` #Get todays date (without the time)
seconds=`date +%s --date "$today"`

for f in *.txt
do
        touch -d "@$seconds" $f
        ((seconds++))
done

#Finished. Now view the result
ls -l --time-style=+"%Y-%m-%d %H:%M:%S"
Related