PowerShell: dates and -replace

I sometimes need to do a naive replacement of dates in a typical UK format to a typical US format.

For example, I might want to take

The Battle of Hastings took place on 14/10/1066 between Harold and William. The war between the 2 was triggered by Edward the Confessor’s death on 12/06/1066.

, and convert it to:

The Battle of Hastings took place on 10/14/1066 between Harold and William. The war between the 2 was triggered by Edward the Confessor’s death on 06/12/1066

or to…

The Battle of Hastings took place on 10-14-1066 between Harold and William. The war between the 2 was triggered by Edward the Confessor’s death on 06-12-1066

This line achieves the second transformation, assuming the text is in history.txt. Note the single quotes.

$(Get-Content -Path .\history.txt) -replace '([0-9]{2})/+([0-9]{2})/+([0-9]{4})','$2-$1-$3'

psregex02

Gist.

Credit to Don Jones for a similar example.

NotePad++:  As this is essentially Regex after all, I will mention that you can do the same kind of thing in NotePad++ and indeed in anything that has a Regex capability. The NotePad++ case looks like this, where the “Find what” pattern is exactly as for PowerShell, and the “Replace with” differs a bit: [\2/\1/\3]

psregex03

Advertisements

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