【问题标题】:Search and replace with PowerShell使用 PowerShell 进行搜索和替换
【发布时间】:2018-12-18 20:40:02
【问题描述】:

我正在使用下面的 PowerShell 脚本进行搜索和替换,效果很好。

$files = Get-ChildItem 'E:\replacetest' -Include "*.txt" -Recurse | ? {Test-Path $_.FullName -PathType Leaf}

foreach($file in $files)
{
    $content = Get-Content $file.FullName | Out-String
    $content| Foreach-Object{$_ -replace 'hello' , 'hellonew'`
                                -replace 'hola' , 'hellonew' } | Out-File $file.FullName -Encoding utf8
}

问题是脚本还会修改其中没有匹配文本的文件。我们如何忽略没有匹配文本的文件?

【问题讨论】:

  • 是否有任何选项可以忽略一些匹配的文本。例如,该文件还包含诸如 c:/hola/hello.xml 之类的文件路径。我想包含一个正则表达式或条件,以便在 /hola/ 之间不更改 hola 或者如果它是 hello.xml 的文件名并更改其他出现。

标签: powershell powershell-2.0


【解决方案1】:

您可以使用 match 来查看内容是否实际更改。由于您总是使用 out-file 编写文件,因此该文件将被修改。

$files = Get-ChildItem 'E:\replacetest' -Include "*.txt" -Recurse | Where-Object {Test-Path $_.FullName -PathType Leaf}

foreach( $file in $files ) { 
    $content = Get-Content $file.FullName | Out-String
    if ( $content -match ' hello | hola ' ) {
        $content -replace ' hello ' , ' hellonew ' `
                 -replace ' hola ' , ' hellonew ' | Out-File $file.FullName -Encoding utf8
        Write-Host "Replaced text in file $($file.FullName)"
    }    
}

【讨论】:

  • 是否可以输出脚本正在修改的文件?
  • 是否有任何选项可以忽略一些匹配的文本。例如,该文件还包含诸如 c:/hola/hello.xml 之类的文件路径。我想包含一个正则表达式或条件,以便在 /hola/ 之间不更改 hola 或者如果它是 hello.xml 的文件名并更改其他出现。
  • 我在上面添加了它
  • 你可以。我添加了空格,但它不会替换任何以句点结尾且未包含在空格中的内容。 -replace 是一种正则表达式替换方法。您应该查看一些文档以获得更具体的替换。
  • 对不起,我的真正意思不是过滤文件夹和文件名,而是过滤文本文件中的内容。例如文本文件里面的内容是 hola hello C:/hola/hello.txt 我想把它改成 hellonew hellonew C:/hola/hello.txt 它应该只更改文本,并且应该忽略文本文件内文件路径中的匹配文本。
【解决方案2】:

你有一个额外的foreach,你需要一个if声明:

$files = Get-ChildItem 'E:\replacetest' -Include "*.txt" -Recurse | ? {Test-Path $_.FullName -PathType Leaf}

foreach($file in $files)
{ 
  $content = Get-Content $file.FullName | Out-String
  if ($content -match 'hello' -or $content -match 'hola') {
    $content -replace 'hello' , 'hellonew'`
            -replace 'hola' , 'hellonew' | Out-File $file.FullName -Encoding utf8    
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 2010-11-13
    • 2022-01-13
    • 1970-01-01
    • 2017-01-05
    相关资源
    最近更新 更多