Replace the first occurence of a string in a file

后端 未结 2 1560
孤街浪徒
孤街浪徒 2021-01-21 04:24

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.

2条回答
  •  独厮守ぢ
    2021-01-21 04:30

    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.

提交回复
热议问题