Change Date and Time of Creation and Modification of file based on filename in MacOS folder

五迷三道 提交于 2020-08-19 10:21:37

问题


I have a lot of files in folder with filenames like

20190618_213557.mp4
20190620_231105.mp4
20190623_101654.mp4
..

I need to change creation date and time based on filename 20190618_213557=YYYYMMDD_HHMMSS using bash script in terminal


回答1:


MACOS Uses touch -mt to change file creation/modification time. Here is the script:

    #!/bin/bash
    FILES="/Users/shakirzareen/Desktop/untitledfolder/*"
    for f in $FILES         ## f = full path + filename
    do
        t="${f##*/}"            ##remove folder path from filename
        t2="${t//_}"            ##remove _ from filename
        t3="${t2%%.*}"          ##remove file extension part
        touch -mt "$t3" $f  ##set creation and modification time of file
    done



回答2:


I had the same problems trying to set the date from filename, and struggled a lot with the code suggested here.

Have to be careful to use the same variable letter for the loop and in the brackets! for i in... {x:4:2} should be for i in... {i:4:2} at least on mac and finish with a semicolon before done. This code should work:

for i in *.mp4; do
   SetFile -d "${i:4:2}/${i:6:2}/${i:0:4} ${i:9:2}:${i:11:2}:${i:13:2}" "$i";
done



回答3:


To bystanders reading this: Please note that this question and answer are for Mac OS. In Linux there is no file creation time in most cases.


The touch command can change the creation date of your files. From man touch

-t STAMP use [[CC]YY]MMDDhhmm[.ss] instead of current time

So we only have to convert your format YYYYMMDD_hhmmss into touch's format. This can be done with bash's parameter substitution. We exttract the substrings YYYYMMDD (${x:0:8}), hhmm (${x:9:4}), and ss (${x:13:2}) and put them together.

for i in *.mp4; do
    touch -t "${x:0:8}${x:9:4}.${x:13:2}" "$i"
done

More options for touch that might be of interest to you:

-c Do not create the file if it does not exist.
-a Change [only] the access time of the file.
-m Change [only] the modification time of the file.

However, this answer claimed that this would only change the creation date if the specified date was before the current creation date. If that's the case and you want to change the time to something after the original creation date use ...

for i in *.mp4; do
   SetFile -d "${x:4:2}/${x:6:2}/${x:0:4} ${x:9:2}:${x:11:2}:${x:13:2}" "$i"
done

SetFile may have to be installed first.



来源:https://stackoverflow.com/questions/59273834/change-date-and-time-of-creation-and-modification-of-file-based-on-filename-in-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!