2011-09-16 75 views
3

在PowerShell腳本中,要替換文件中第一次出現的字符串,我隨附下面的代碼,它跟蹤變量是否進行替換。替換文件中字符串的第一次出現

有沒有更優雅(習慣)的方式來做到這一點?

$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 

回答

3

如果是XML,把它處理XML:

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

SelectSingleNode將選擇第一個版本元素。然後替換它的內部內容並保存到新文件中。如果您只想專門替換,請爲內部內容添加一個檢查號碼6.1.26.p1

+0

我甚至沒有注意到它是XML。那樣的話,肯定是這樣做的。 – EBGreen

4

所以我們說,你有一個名爲test.txt文件,它的內容是:

one 
two 
four 
four 
five 
six 
seven 
eight 
nine 
ten 

你想改變只是四的第一個實例是三來代替:

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