Sarvavyapi
Sarvavyapi

Reputation: 850

Powershell - retain leading zeros

My input file (csv) is read like this:

$recvCSV = Import-Csv $g_inputFile

and looks like below. The address column indicates the MAC address and I want to retain the leading zeros.

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

My output should be like this:

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

These are my attempts at getting the leading zeros:

$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 }

I referred to the below sites:

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/

Please let me know what I am doing wrong.

EDIT: My main concern is, how to ensure that the zero is inserted at the correct place (90 vs 09)? I have given a couple of samples below.

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

Upvotes: 0

Views: 1966

Answers (2)

Keith Hill
Keith Hill

Reputation: 201692

Just for fun, here's one more option using regex replace:

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

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

Upvotes: 1

mjolinor
mjolinor

Reputation: 68273

Not the prettiest thing I ever wrote, but:

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

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

This one's a little prettier, I think:

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

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

Upvotes: 1

Related Questions