10

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!

1
  • If you have a date string in some variable ($date) then to reformat it easily in powershell: (Get-Date $date).ToString('yyyy-dd-MM HH:mm:ss') Commented Jan 31, 2018 at 17:19

3 Answers 3

22

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Michael, but unfortunately I am still getting the result: \3-\2-\1 23:00:43 with this script. Am I missing something?
@AshBestos: Did you remember to save your script after copying this in? That's my first guess.
Aha, I was actually checking a file called text.txt in a different directory! Oops! Thanks very much for your help.
4

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)'

Comments

2

try

Foreach-Object {$_-replace "([0-9]+)/+([0-9]+)/+([0-9]+)", '$3-$2-$1'}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.