2012-02-07 53 views
3

我有一些文本文件中出現了一些字符串「bad」。我想用good1,good2,good3,,, good100等替換每個出現的「壞」。動態替換文件中每個字符串的出現

我想這一點,但它與過去的數字替換所有出現,good100

$raw = $(gc raw.txt) 

for($i = 0; $i -le 100; $i++) 
{ 
    $raw | %{$_ -replace "bad", "good$($i)" } > output.txt 
} 

如何做到這一點?

回答

3

試試這個:

$i = 1 
$raw = $(gc raw.txt) 
$new = $raw.split(" ") | % { $_ -replace "bad" , "good($i)" ; if ($_ -eq "bad") {$i++} } 
$new -join " " | out-file output.txt 

這是一件好事,如果raw.txt是單行和包含單詞「壞」總是用一個空格separed「」是這樣的:阿爾法壞公測壞伽馬壞(和等等...評論後)

編輯:

多行TXT:

$i = 1 
$new = @() 
$raw = $(gc raw.txt) 
for($c = 0 ; $c -lt $raw.length ; $c++) 
{ 
$l = $raw[$c].split(" ") | % { $_ -replace "bad" , "good($i)" ; if ($_ -eq "bad") {$i++} } 
$l = $l -join " " 
$new += $l 
} 

$new | out-file output.txt 
+0

我覺得沒有拆分的方法,因爲它拋出,這種方法不存在錯誤。 – Animesh 2012-02-07 10:01:07

+0

不應該'split()'更好? – 2012-02-07 10:02:07

+0

你可以試試這個:$ raw.gettype()並告訴我是否返回[string]?字符串類型有split()方法! – 2012-02-07 10:04:07

2

對於這樣的事情,我一般使用正則表達式替換::超載,需要一個Matchevaluator:

$evaluator ={ 
$count++ 
"good$count" 
} 

gc raw.txt | %{ [Regex]::Replace($_,"bad",$evaluator) } 

評價者也得到了匹配組作爲參數,所以你可以做一些高級替換它。

+0

+1使用評估者的簡單性 – Benja 2014-05-09 19:55:38

2

這裏的另一種方式,一次更換隻有一個比賽:

$raw = gc raw.txt | out-string 
$occurrences=[regex]::matches($raw,'bad') 
$regex = [regex]'bad' 

for($i=0; $i -le $occurrences.count; $i++) 
{ 
    $raw = $regex.replace($raw,{"good$i"},1) 
} 

$raw 
相關問題