【问题标题】:How to replace dates in text file with Powershell using regular expressions如何使用正则表达式用 Powershell 替换文本文件中的日期
【发布时间】:2012-06-22 18:51:51
【问题描述】:

我在这方面做了很多搜索,还没有找到答案,但我觉得我很接近了!

我在文本文件中有以下格式的日期:18/06/2012 23:00:43 (dd/mm/yyyy HH:MM:SS),我想使用 Powershell 将其转换为:2012-18-06 23:00:43 (yyyy-dd-mm HH:MM:SS)

要使用正则表达式在文本编辑器中执行转换,我会这样做:

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

Replace with: \3-\2-\1

所以我尝试在以下 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

但这会导致以下不良变化:

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

谁能帮我解决这个问题?

非常感谢!

【问题讨论】:

  • 如果您在某个变量 ($date) 中有日期字符串,那么在 powershell 中轻松重新格式化它:(Get-Date $date).ToString('yyyy-dd- MM HH:mm:ss')

标签: regex date powershell replace


【解决方案1】:

这就是你想要的:

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

捕获组引用是使用$ 符号完成的,而不是反斜杠。此外,要按编号引用捕获的组,you must use single quotes around the replacement string;否则,PowerShell 会将任何 $ 符号解释为对先前定义的变量的引用,在这种情况下,这将导致字符串 "--",因为不存在此类变量。

【讨论】:

  • 谢谢迈克尔,但不幸的是我仍然得到结果:\3-\2-\1 23:00:43 使用这个脚本。我错过了什么吗?
  • @AshBestos:你还记得复制后保存你的脚本吗?这是我的第一个猜测。
  • 啊哈,我实际上是在另一个目录中检查一个名为 text.txt 的文件!哎呀!非常感谢您的帮助。
【解决方案2】:

-replace 运算符支持与 .NET 中的 Regex.Replace() 函数相同的替换文本占位符。 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".

'($3-$2-$1)'代替"(\3-\2-\1)"

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

【讨论】:

    【解决方案3】:

    试试

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

    【讨论】:

      猜你喜欢
      • 2017-08-09
      • 1970-01-01
      • 2018-03-16
      • 2022-11-17
      • 2017-10-18
      • 1970-01-01
      • 2020-04-03
      相关资源
      最近更新 更多