使用Powershell替换文本文件中的一串字符串字符

时间:2016-02-02 01:35:52

标签: powershell windows-7 powershell-v3.0

使用PowerShell代码替换文件夹中的文本文件中的一组字符(包含大量文本文件)。有没有办法可以为文件夹中的所有文件执行此操作?

问题是,当我运行代码(New_NOV_1995.txt)时它会创建一个新文件,但它不会更改新文件中的任何字符。

 $lookupTable = @{
'¿' = '|' 
'Ù' = '|' 
'À' = '|' 
'Ú' = '|' 
'³' = '|' 
'Ä' = '-'
}

$original_file = 'C:\FilePath\NOV_1995.txt'
$destination_file =  'C:\FilePath\NOV_1995_NEW.txt'

Get-Content -Path $original_file | ForEach-Object { 
    $line = $_

    $lookupTable.GetEnumerator() | ForEach-Object {
        if ($line -match $_.Key)
        {
            $line = $line -replace $_.Key, $_.Value
        }
    }
   $line
} | Set-Content -Path $destination_file

2 个答案:

答案 0 :(得分:0)

虽然这样的事情会奏效,但性能可能会有问题。我唯一的测试是在一个包含$lookupTable

的小文件上
 $lookupTable = @{
'¿' = '|' 
'Ù' = '|' 
'À' = '|' 
'Ú' = '|' 
'³' = '|' 
'Ä' = '-'
}

$original_file = 'C:\FilePath\NOV_1995.txt'
$destination_file =  'C:\FilePath\NOV_1995_NEW.txt'

$originalContent = Get-Content -Path $original_file
$lookupTable.GetEnumerator() | % {
   $originalContent = $originalContent -replace $_.Key,$_.Value
}
$originalContent | Out-File -FilePath $destination_file

答案 1 :(得分:0)

你所拥有的代码实际上对我有用。 文件可能存在编码问题。当您使用Get-Content $path将其读入控制台时,您的文件是否正确?如果文件看起来不正确,您可能需要使用的-Encoding开关 Set-ContentGet-Content cmdlet。

改善您当前的逻辑。

我将你的$lookuptable改为一对psobjects。由于您在大多数情况下都在进行相同的替换,因此我将它们组合成一个正则表达式。

下一部分我哼唱和讨厌,但是因为,在我提议的改变之后,你只做了两次替换,我想你可以将两者连成一条替换线。否则你可以在那里有一个foreach-object,但我认为这更简单,更快。

这样我们就不需要测试匹配了。 -replace正在为我们进行测试。

$toPipe = [pscustomobject]@{
    Pattern = '¿|Ù|À|Ú|³'
    Replacement = "|"
}
$toHypen =  [pscustomobject]@{
    Pattern = 'Ä'
    Replacement = "-"
}

$path = "c:\temp\test\test"
Get-ChildItem -Path $path | ForEach-Object{
    (Get-Content $_.FullName) -replace $toPipe.Pattern,$toPipe.Replacement -replace $toHypen.Pattern,$toHypen.Replacement | 
            Set-Content $_.FullName 
}

请注意,这将更改原始文件。鼓励测试。

Set-ContentGet-Content在性能方面不是最好的,因此您可能需要考虑使用[IO.File]::ReadAllLines($file)及其合作伙伴静态方法[IO.File]::WriteAllLines($file)

相关问题