Home > Uncategorized > Padding numbers with zeros using regular expressions and powershell

Padding numbers with zeros using regular expressions and powershell

I had a very small scripting task today. A bunch of text files contained numbers that should be padded with initial zeros.

For example, the following text:

some text
identifier: “12”
some text
identifier: “8”
some text

Should be replaced by:

some text
identifier: “012”
some text
identifier: “008”
some text

 

Using regular expressions this task can be accomplished by:

function Pad-Numbers
{
    process
    {
        $text = Get-Content $_.FullName
        $text = $text -creplace “identifier: `”(\d)`””, “identifier: `”00`$1`””
        $text = $text -creplace “identifier: `”(\d\d)`””, “identifier: `”0`$1`””
        Set-Content -path $_.FullName -value $text
    }
}

Get-ChildItem -path data -filter *.txt | Pad-Numbers

A good source for regular expressions for powershell users is http://www.regular-expressions.info/powershell.html.

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: