2013-10-25 97 views
0

我的輸入文件(CSV)讀這樣的:PowerShell的 - 保留前導零

$recvCSV = Import-Csv $g_inputFile 

,看起來像下面。地址列表示MAC地址,我想保留前導零。

currentTime, SeqNum, Address, Location 
1382393056692, 0, 
1382393056860, 0, 38:1c:4a:0:8d:d 
1382393057194, 1, 
1382393057360, 1, 38:1c:4a:0:8d:d 

我的輸出應該是這樣的:

38:1c:4a:00:8d:0d 

這是我嘗試在獲得前導零:

$recvCSV | ? { $null, '' -notcontains $_.Address } | Group-Object Address | % { "{0:00 0:00 0:00 0:00 0:00 0:00}" -f $_.Name } 
$recvCSV | ? { $null, '' -notcontains $_.Address } | Group-Object Address | % { "[string]::format "0:00 0:00 0:00 0:00 0:00 0:00", $_.Name } 
$recvCSV | ? { $null, '' -notcontains $_.Address } | Group-Object Address | % { "0:00;0:00;0:00;0:00;0:00;0:00" -f $_.Name } 

我提到了以下網站:

http://blog.stevex.net/string-formatting-in-csharp/ 
http://msdn.microsoft.com/en-us/library/fbxft59x.aspx 
http://jdhitsolutions.com/blog/2012/01/format-leading-zeros-in-powershell/ 

請讓我知道我在做什麼錯誤的。

編輯: 我主要關心的是,如何確保將零點插入正確的位置(90 vs 09)?下面給出了幾個樣本。

38:1c:4a:__:8d:_d ==> 38:1c:4a:00:8d:0d 
__:9_:4c:11:22:33 ==> 00:90:4c:11:22:33 

回答

1

不是我寫過的最漂亮的事情,但:

$string = '38:1c:4a:0:8d:d' 
($string.Split(':') |% {('0'+$_)[-2..-1] -join ''}) -join ':' 

38:1c:4a:00:8d:0d 

這一個有點漂亮,我想:

$string = '38:1c:4a:0:8d:d' 
($string.Split(':').PadLeft(2,'0')) -join ':' 

38:1c:4a:00:8d:0d 
1

只是爲了好玩,這裏是使用正則表達式多了一個選擇替換:

$string = '3:1c:4a:0:c:d' 
$string -replace '(?<=:|^)([0-9a-f])(?=(:|$))','0$1' 

03:1c:4a:00:0c:0d