【问题标题】:convert unix timestamp in filename在文件名中转换 unix 时间戳
【发布时间】:2012-07-08 22:41:36
【问题描述】:

我使用 MacOSX Lion,但我对 Windows 解决方案也很满意,因为我在虚拟机中安装了 Windows XP:

我有数百个文件名中带有 unix 时间戳的文件,如下所示:

1341131403_-_db123456.sql.gz
1341390599_-_db123456.sql.gz
1341563401_-_db123456.sql.gz

我希望将时间戳转换为可读时间戳,并使用该可读时间戳重命名文件,如下所示:

2012-07-01 08-30-03.sql.gz
2012-07-04 08-29-59.sql.gz
2012-07-06 08-30-01.sql.gz

我在一个 applescript 解决方案上花了几个小时,但没有成功:

on open (the_input)
tell application "Finder"
set the_files to every item of the_input
set the_count to count of the_files
repeat with i from 1 to the_count
set current_file to item i of the_files
set old_name to (name of current_file) as string
set old_name to trim_line(old_name, "_-_db123456. sql. gz", 1)
set new_name to (result of uts_convert(old_name)) as string
set the name of current_file to (new_name & file type of current_file)
end repeat
end tell
end open

on uts_convert(input)
set shellcommand1 to "date -r "
set shellcommand2 to " \"+%Y-%m-%d %H-%M\""
set the_output to do shell script (shellcommand1 & input & shellcommand2)
return the_output
end uts_convert

感谢任何帮助!我不在乎它是通过 applescript 还是简单的终端命令或其他方式完成的。

提前致谢!

【问题讨论】:

    标签: macos terminal applescript unix-timestamp


    【解决方案1】:

    试试:

    tell application "Finder" to set theFiles to every file of folder ((path to desktop) & "testfolder" as text)
    set {TID, text item delimiters} to {text item delimiters, "_-_"}
    repeat with aFile in theFiles
        set timestamp to text item 1 of (name of aFile as text)
        set newName to do shell script "date -r " & timestamp & " '+%Y-%m-%d %H-%M-%S'"
        set aFile's name to (newName & ".sql.gz")
    end repeat
    set text item delimiters to TID
    

    【讨论】:

      【解决方案2】:

      这是一个简单的 Perl 解决方案:

      opendir($dir, ".");
      while ($f = readdir($dir)) {
          if ($f =~ m/^(\d+)_-_db\d+\.sql\.gz/) {
              ($s, $i, $h, $d, $m, $y) = gmtime($1);
              rename($f, sprintf("%4d-%02d-%02d %02d-%02d-%02d.sql.gz", $y + 1900, $m + 1, $d, $h, $i, $s));
          }
      }
      closedir($dir);
      

      将其保存到 renamethings.pl 或与文件相同的文件夹中的任何内容并运行:

      perl renamethings.pl
      

      最好先备份文件以防万一出现问题。

      【讨论】:

      • 你的 sprintf 远不如 strftime("%Y-%m-%d %H-%M-%S", gmtime($1))。使用 POSIX 'strftime'。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-29
      • 2013-04-07
      • 2013-12-14
      • 2010-10-25
      相关资源
      最近更新 更多