2013-10-09 143 views
-2

我有一個列出日期的數據文件。日期格式爲m/d/yyyy。一個例子如下所示:使用Perl從日期提取月份和日期

1/1/2011 
1/10/2011 
10/1/2011 
10/10/2011 

我的問題是,我怎麼能提取月份和日期,這樣我就可以在不同的文件,其存儲在兩個單獨列?例如,我想顯示爲

Month Day 
1  1 
1  10 
10  1 
10  10 
+2

你應該能夠很容易地做到這一點使用'split'。 – squiguy

+5

**嘗試自己寫一些東西**,然後如果它不起作用,請特別向我們展示您做了什麼,以便我們可以幫助您。你開始吧,我們幫忙。我們不會爲你寫信。向我們展示您嘗試過的實際代碼,然後我們可以從那裏幫助您。如果你只是先嚐試​​一下,你很可能會接近答案。 –

回答

0

假設你所有的日期遵循相同的格式,那麼你甚至不需要一個正則表達式。該解決方案的一般形式如下:

my ($month, $day, $year) = split([email protected]/@, $date); 

如果你從一個文件dates.txt閱讀,你可以這樣使用它:

open my $DATES, '<', 'dates.txt' 
    or die "Couldn't open dates.txt: $!\n"; 

while (my $date = <$DATES>) { 
    $date =~ [email protected]\r|\[email protected]@g; # get rid of trailing newlines, however formatted 
    my ($month, $day, $year) = split([email protected]/@, $date); 
    # whatever you need to do with the date parts, do here 
}; 

close DATES; 

被告知,根據您的教育機構的學術榮譽政策時,您可能需要引用這個堆棧溢出的答案作爲參考,當你打開作業,在各種處罰的痛苦,並可能包括驅逐出境。

0

使用perl

perl -pe 's#(\d+)/(\d+)/\d+#$1\t$2#' file > new_file 

使用sed

sed -r 's#([0-9]+)/([0-9]+)/[0-9]+#\1\t\2#' file > new_file 
-1

使用split與切片:

#!/usr/bin/perl 
use warnings; 
use strict; 
use feature 'say'; 

for my $date (qw(1/1/2011 
       1/10/2011 
       10/1/2011 
       10/10/2011)) { 
    say join "\t", (split m{/}, $date)[0, 1]; 
} 
+0

'使用strict'和隱式'$ _'?有趣的組合。 –

+0

@AaronMiller:好的,加了一個名字。 – choroba

1

my ($Day, $Month, $Year) = split(m{/}, $Line);

0

我相信,而不是使用split,是最清晰的使用正則表達式

my ($m, $d, $y) = $date =~ /\d+/g; 

這裏提取的字符串中的所有數字字段中顯示的想法一個完整的程序。

use strict; 
use warnings; 

my @dates = qw< 
    1/1/2011 
    1/10/2011 
    10/1/2011 
    10/10/2011 
>; 

print "Month Day\n"; 

for (@dates) { 
    my ($m, $d, $y) = /\d+/g; 
    printf "%-7d %-7d\n", $m, $d; 
} 

輸出

Month Day 
1  1  
1  10  
10  1  
10  10  
相關問題