Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace dates in text file with Powershell using regular expressions

I've done much searching on this and haven't worked out the answer, but I feel like I am close!

I have dates in a text file in the following format: 18/06/2012 23:00:43 (dd/mm/yyyy HH:MM:SS) which I want to convert to: 2012-18-06 23:00:43 (yyyy-dd-mm HH:MM:SS) using Powershell.

To perform the conversion in a text editor using regular expressions I would do this:

Find: ([0-9]+)/+([0-9]+)/+([0-9]+)

Replace with: \3-\2-\1

So I have tried using this same logic in a the following Powershell script:

(Get-Content C:\script\test.txt) | 
Foreach-Object {$_ -replace "([0-9]+)/+([0-9]+)/+([0-9]+)", "(\3-\2-\1)"} | 
Set-Content C:\script\test.txt

but that results in the following undesired change:

\3-\2-\1 23:00:43

Can anybody help me nail this?

Many thanks in advance!

like image 259
AshBestos Avatar asked Jun 20 '12 15:06

AshBestos


People also ask

How do I replace text in a text file in PowerShell?

One way to do that is to use the -replace operator. This PowerShell operator finds a string and replaces it with another. Using the example file contents, we can provide the search string foo with the replacement string bar which should make the file contents foo foo baz now.

How do you match text in PowerShell?

If you want to find the string at certain positions within the string, use ^ to indicate the beginning of the string and $ to indicate the end of the string. To match the entire string, use both. Note the ^ at the start and the $ at the end to ensure that the entire input string must match.


2 Answers

This is what you want:

(Get-Content C:\script\test.txt) | 
Foreach-Object {$_ -replace "([0-9]+)/+([0-9]+)/+([0-9]+)", '$3-$2-$1'} | 
Set-Content C:\script\test.txt

Capturing group references are done with the $ symbol, not a backslash. Also, to reference a captured group by number, you must use single quotes around the replacement string; otherwise, PowerShell will interpret any $ symbol as a reference to a previously defined variable, which in this case will result in the string "--" since no such variables exist.

like image 157
Michael Myers Avatar answered Sep 30 '22 05:09

Michael Myers


The -replace operator supports the same replacement text placeholders as the Regex.Replace() function in .NET. E.g. $& is the overall regex match, $1 is the text matched by the first capturing group, and ${name} is the text matched by the named group "name".

Instead of "(\3-\2-\1)" use '($3-$2-$1)'

'06/18/2012 23:00:43' -replace "(\d+)/(\d+)/(\d+)", '($3-$2-$1)'

like image 40
Akim Avatar answered Sep 30 '22 05:09

Akim