开发者

Replace the first occurence of a string in a file

开发者 https://www.devze.com 2023-04-05 16:01 出处:网络
In a PowerShell script, to replace the first occurrence of a string in a file I came with the code below, which keeps track in a variable whether the replacement was made.

In a PowerShell script, to replace the first occurrence of a string in a file I came with the code below, which keeps track in a variable whether the replacement was made.

Is there a more elegant (idiomatic) way of doing this?

$original_file = 'pom.xml'
$destination_file =  'pom.xml.new'

$done = $false
(Get-Content $original_file) | Foreach-Object {
    $done
    if ($done) {
        $_
    } else {
        $result = $_ -replace '<version>6.1.26.p1</version>', '<version>6.1.26.p1-SNAPSHOT</version>'
        if ($result -ne $_) 开发者_开发问答{
            $done = $true
        }
        $result
    }
} | Set-Content $destination_file


So let's say that you had a file named Test.txt and it's contents were:

one
two
four
four
five
six
seven
eight
nine
ten

And you want to change just the first instance of four to be three instead:

$re = [regex]'four'
$re.Replace([string]::Join("`n", (gc C:\Path\To\test.txt)), 'three', 1)


If it is xml, handle it as xml:

$xml = [xml](gc $original_file)
$xml.SelectSingleNode("//version")."#text" = "6.1.26.p1-SNAPSHOT"
$xml.Save($destination_file)

SelectSingleNode will select the first version element. Then replace it's inner content and save to the new file. Add a check for the inner content being 6.1.26.p1 if you want to specifically replace only that.

0

精彩评论

暂无评论...
验证码 换一张
取 消