powershell - 从文件和文件中搜索替换为另一个文件

时间:2014-05-26 05:34:59

标签: powershell

我想从文件中搜索字符串集合并替换为另一个文件。例如:

文件A.txt(搜索模式)

文件B.txt(实际文件)

所以,在这里,我想将文件A中给出的所有字符串替换为文件B(比较/替换文件A的所有行与文件B的每一行)。我想以简单的方式实现,也许使用foreachobject循环。请帮帮我??

1 个答案:

答案 0 :(得分:0)

为了获得良好的学习体验,我在下面创建了一个cmdlet。内联注释应该能够指导您如何完成它。

function Get-ReplacedText
{
    [CmdletBinding()]
    Param
    (
        # Path containing the text file to be searched.
        $FilePath,

        # Path containing the patterns to be searched and replaced.
        $SearchPatternFilePath
    )

    # Patterns will be read in full for fast access.
    $patterns = Get-Content -Path $SearchPatternFilePath 

    # Use the StreamReader for efficiency.
    $reader = [System.IO.File]::OpenText($FilePath)

    # Open the file
    while(-not $reader.EndOfStream)
    {
        $line = $reader.ReadLine()

        foreach ($pattern in $patterns) {

            $search, $replacement = $pattern.Split()

            # Replace any searched text that exist with replacement.
            $line = $line -replace $search, $replacement
        }

        # Get the replaced line out of the pipeline.
        $line
    }

    #Close the file.
    $reader.Close()
}

请注意,您正在阅读模式的文件应该是这样构造的,并且搜索模式和替换文本之间有一个空格。此外,搜索模式可以是Regexp格式。

searchpattern1 replacement1
searchpattern2 replacement2

最后,使用cmdlet的示例

Get-ReplacedText -FilePath txtfile.txt -SearchPatternFilePath searchpattern.txt | Out-File -FilePath result.txt -Encoding ascii
相关问题