【问题标题】:Powershell match Regex and ReplacePowershell 匹配正则表达式和替换
【发布时间】:2013-03-01 04:53:48
【问题描述】:

我正在搜索一个大文件以查找和替换无效日期。我使用 REGEX 表达式来定位日期,然后确定它们是否有效。如果脚本发现无效日期,则需要将日期替换为当前日期。出于审计目的,我需要记录无效字符串和发现错误的行号。到目前为止(在 SO 的一些事先帮助下)我已经能够找到无效的日期,但我无法成功地更改它们。

这是我用来定位无效日期的代码。如何一次性定位和更改日期?

$matchInfos = @(Select-String -Pattern $regex -AllMatches -Path $file)
foreach ($minfo in $matchInfos)
{
    #"LineNumber $($minfo.LineNumber)"
    foreach ($match in @($minfo.Matches | Foreach {$_.Groups[0].value}))
    {
        if (([Boolean]($match -as [DateTime]) -eq $false ) -or ([DateTime]::parseexact($match,"MM-dd-yyyy",$null).Year -lt "1800")) {
            Write-host "Invalid date on line $($minfo.LineNumber) - $match"
            #Add-Content -Path $LOGFILE -Value "Invalid date on line $($minfo.LineNumber) - $match"

            # Replace the invalid date with a corrected one
            Write-Host "Replacing $match with $(Get-Date -Format "MM-dd-yyyy")"
            #Add-Content -Path $LOGFILE -Value "Replacing $match with $(Get-Date -Format "MM-dd-yyyy")"

        }
    }
 }

【问题讨论】:

    标签: regex powershell


    【解决方案1】:

    您必须写出包含更改的临时文件并用临时文件替换该文件。这是我写的一篇文章,它将为你完成这部分:

    Windows IT Pro: Replacing Strings in Files Using PowerShell

    使用示例:

    replace-filestring -pattern 'find' -replacement 'replace' -path myfile.txt -overwrite
    

    使用此命令,脚本将读取 myfile.txt,将 'find' 替换为 'replace',将输出写入临时文件,然后将 myfile.txt 替换为临时文件。 (如果没有 -Overwrite 参数,脚本只会输出 myfile.txt 的更改内容。)

    比尔

    【讨论】:

      【解决方案2】:
      $lines = get-content $file
      $len = $lines.count
      $bad = @{}
      for($i=0;$i-lt$len;$i++){
          if($lines[$i] -match ""){
              $bad_date = $lines[$i].substring(10) #Get the bad date
              $good_date = Get-Date -Format G
              $bad["$i"] += @($line[$i])
              $lines[$i] = $lines[$i].Replace($bad_date,$good_date)
          }
      }
      $lines > $NewFile
      $bad > $bad_date_file
      

      这里有一些我将如何解决这个问题的伪代码。不确定你的文件有多大。阅读和写作可能会很慢。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-03
        • 1970-01-01
        • 1970-01-01
        • 2012-05-16
        • 2011-09-15
        • 2012-11-23
        • 1970-01-01
        相关资源
        最近更新 更多