2012-07-08 83 views
0

我使用MacOSX的狮子,但我也很高兴,支持Windows的解决方案,因为我有Windows XP的虚拟机:转换Unix时间戳的文件名

我有数百个文件,用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 

我已经有余度T ON一个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或简单的终端命令或其他方式完成的。

在此先感谢!

回答

0

尝试:

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 
0

这里有一个简单的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 

,很可能会谨慎地首先备份文件,以防万一出现问题。

+0

你的sprintf是很整齐的的strftime( “%Y-%间%d%H-%M-%S”,gmtime的($ 1))。使用POSIX'strftime'。 – LeoNerd 2012-07-09 09:49:49