2012-02-07 52 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 
相关问题