简体   繁体   English

如何使用正则表达式使用Powershell替换文本文件中的日期

[英]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. 我在文本文件中的日期格式如下: 18/06/2012 23:00:43 (dd/mm/yyyy HH:MM:SS)我要转换为: 2012-18-06 23:00:43 (yyyy-dd-mm HH:MM:SS)使用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: 所以我尝试在以下Powershell脚本中使用相同的逻辑:

(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 \\ 3- \\ \\ 2- \\ 1 23:00:43

Can anybody help me nail this? 任何人都可以帮我解决这个问题吗?

Many thanks in advance! 提前谢谢了!

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. 否则,PowerShell会将任何$符号解释为对先前定义的变量的引用,在这种情况下将导致字符串"--"因为不存在这样的变量。

The -replace operator supports the same replacement text placeholders as the Regex.Replace() function in .NET. -replace运算符支持与.NET中的Regex.Replace()函数相同的替换文本占位符。 Eg $& 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" . 例如$&是整个正则表达式匹配,$ 1是第一个捕获组匹配的文本,$ {name}是命名组“name”匹配的文本

Instead of "(\\3-\\2-\\1)" use '($3-$2-$1)' 而不是"(\\3-\\2-\\1)"使用'($3-$2-$1)'

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

尝试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM