替换文件中引号之间的字符串内容

时间:2016-01-22 13:58:10

标签: powershell

我已经使这个循环迭代了一些我想要替换内容的文件。

我要替换的内容是一个字符串,它看起来像这样:foo="1"

我需要你的帮助是如何找到字符串(我猜是regexp)并使用新值更新文件,例如2

$files = Get-ChildItem -Recurse -Filter "*.config"

foreach ($file in $files)
{
    Get-Content $file.FullName
}

Read-Host

3 个答案:

答案 0 :(得分:2)

你可以试试正则表达式。实施例

$files = Get-ChildItem -Recurse -Filter "*.config"

$find = 'foo=".*?"'
$replace = 'foo="4"'

foreach ($file in $files)
{
    Get-Content $file.FullName |
    Foreach-Object { $_ -replace $find, $replace } |
        Set-Content $file.Fullname
    }
}

Read-Host

或者只修改匹配的文件:

$files = Get-ChildItem -Recurse -Filter "*.config"

$find = 'foo=".*?"'
$replace = 'foo="4"'

foreach ($file in $files)
{
    $content = Get-Content $file.FullName
    if(Select-String -InputObject $content -Pattern $find -Quiet) {
        $content |
        Foreach-Object { $_ -replace $find, $replace } |
        Set-Content $file.Fullname
    }
}

Read-Host

答案 1 :(得分:2)

根据问题中的示例代码,我假设您正在尝试更新.NET配置文件(即web.configapp.config文件。)

鉴于这些文件确实是XML文件,您可能希望将它们视为:

$files = Get-ChildItem -Recurse -Filter "*.config"

foreach ($file in $files)
{
    # Create an XmlDocument object from the file
    $configXml = [xml](Get-Content $file.FullName)

    # Find all the nodes in the document
    $xmlNodes  = $configXml.SelectNodes('//*')

    # Keep track of whether we make changes or not
    $changeCount = 0

    foreach($node in $xmlNodes)
    {
        # Check if node has a "foo" attribute
        if($node.HasAttribute('foo'))
        {
            # Set 2 as the value
            $node.SetAttribute('foo',2)
            $changeCount++
        }
    }

    if($changeCount)
    {
        # At least one node was updated, save to file
        $configXml.Save($file.FullName)
    }
}

答案 2 :(得分:1)

这应该回答你的问题

$files = Get-ChildItem -Recurse -Filter "*.config"

foreach ($file in $files)
{
    $fileContent = Get-Content $file.FullName
    $newContent = $fileContent -replace 'foo="1"', 'foo="2"'
    Set-Content $file.FullName $newContent
}

进一步阅读:Use PowerShell to Replace Text in Strings

相关问题