2013-08-30 73 views
0

如何在perl中追加系統日期到文件名?如何將系統日期附加到perl中的文件名?

因爲我對perl編程非常陌生,你能給我一個簡單的例子,上面的查詢。

+1

您正在創建新文件還是您有現有文件要重命名?你試過什麼了? – RobEarl

+3

@JustCoder你試圖自己研發這個問題。一個快速谷歌可能會幫助你出去! –

回答

1

這可能會幫助你出去!

#!/usr/bin/perl 
my $date=`date +%Y%m%d`; 
chomp($date); 
my $source_file="/tmp/fileName_.tgz"; 
my $destination_file="/misc/fileName_" . $date . ".tgz"; 
print "$source_file\n"; 
print "$destination_file\n"; 
system("sudo mv /tmp/fileName_.tgz /misc/fileName_$date.tgz"); 

或試試這個

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); 
$year += 1900; 

my $out = "$dir/$host-$mday-$mon-$year" 

或這一個

# grab the current time 
my @now = localtime(); 

# rearrange the following to suit your stamping needs. 
# it currently generates YYYYMMDDhhmmss 
my $timeStamp = sprintf("%04d%02d%02d%02d%02d%02d", 
         $now[5]+1900, $now[4]+1, $now[3], 
         $now[2],  $now[1], $now[0]); 

# insert stamp into constant portion of file name. 
# the constant portion of the name could be included 
# in the sprintf() above. 
my $fileName = "File$timeStamp.log"; 
+1

你的第一個例子依賴於一個叫做'date'的外部程序,因此它不是可移植的。你的第二個例子包含一個錯誤(該月將是錯誤的)。你所有的例子都會忽略POSIX :: strftime()的存在,這會讓這一切變得更容易。 –

4

POSIX模塊strftime()功能給出了一個簡單的方法來得到你想要的任何格式的日期。

#!/usr/bin/perl 

use strict; 
use warnings; 
use 5.010; 
use POSIX 'strftime'; 

my $date = strftime '%Y-%m-%d', localtime; 
say $date; 

然後,您可以在文件的文件名中使用該字符串。如果您正在重命名文件,則可以使用File::Copy模塊中的move()

相關問題