David E
David E

Reputation: 37

Set creation date from date in filename

I'd like create an automator service to change the creation date of files from the date in the filename.

Filename :"2014-02-02 Lorem Ipsum.md" or "20190828719 Lorem Ipsum.md".

If there's a way to build both into one service that's amazing, but two would also work. Don't care about time, just date.

#Note: Filename = "2014-02-02 Lorem Ipsum.md"

$ BASENAME=$(basename $f)
$ TITLE=${BASENAME%.*}

$ echo "$TITLE" | cut -d" " -f1

2014-02-02
Lorem
Ipsum

$ #TOUCH - Something

I'm assuming I'll use some sort of for f do done to loop through all selected files.

Upvotes: 1

Views: 1302

Answers (1)

oliv
oliv

Reputation: 13249

You could use sed to format the time and give it to touch:

for i in *.md; do 
   touch -d $(sed 's/[^0-9]//g;s/^\(.\{8\}\).*/\1/' <<< "$i") "$i"
done

The sed regex removes all none digit characters and takes only the first 8 remaining characters.

The -d option of touch set the modification time to the given date. This option might be GNU specific one and not available on macosx system.

On macosx, you may use the command SetFile (credits: here):

for i in *.md; do 
   SetFile -d $(sed 's/[^0-9]//g;s/\(.\{4\}\)\(.\{2\}\)\(.\{2\}\).*/\1\/\2\/\3 00:00:00/' <<< "$i") "$i"
done

Upvotes: 2

Related Questions