2013-02-22 86 views
1

我想導入CSV並篩選出具有一定的正則表達式的數據。輸入CSV示例:進口-CSV使用正則表達式

John;Doe;18 
Peter;Test;21 

我想篩選出個人的名字,例如:我只想看到與姓氏開頭的「d」的人員和那些誰是20年以上。

如何將過濾後的數據寫入到一個新的數組?下面是我到目前爲止寫的一段代碼:

$persons = import-csv -Header "surname", "lastname", "age" -delimiter ";" data.csv 
$persons | ForEach-Object { 
if $_.lastname -match "^d" { 
    #? 
} 

非常感謝

回答

0

嘗試以下操作:

$persons = Import-Csv -Header "surname", "lastname", "age" -Delimiter ";" data.csv | where { 
    $_.lastname -match '^d' -and $_.age -ge 20 
} 

它過濾掉紀錄以姓氏開頭「 d「,年齡在20歲或以上。最後,將結果保存在一個名爲$persons

0
$persons | Where-Object {$_.LastName -like "d*" -and $_.Age -gt 20} 
0

試試這個正則表達式

^([^;]*);([^;]*);([^;]*)$ 

用Perl試了一下數組

#!/usr/bin/perl 

use strict; 

while (<>) { 

    if (/^([^;]*);([^;]*);([^;]*)$/){ 
     print "first =". $1 . "\n"; 
     print "last =". $2 . "\n"; 
     print "age =". $3 . "\n"; 
    } 
} 

這給該輸出

first =John 
last =Doe 
age =18 

first =Peter 
last =Test 
age =21 

但是焦點正則表達式