【问题标题】:Powershell - retain leading zerosPowershell - 保留前导零
【发布时间】:2013-10-25 21:59:54
【问题描述】:

我的输入文件 (csv) 是这样读取的:

$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

【问题讨论】:

    标签: powershell format


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      只是为了好玩,这里还有一个使用正则表达式替换的选项:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-01
        • 2020-06-11
        • 2014-09-01
        • 2014-02-14
        • 2017-04-03
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        相关资源
        最近更新 更多