3

I have some text file which has some occurrences of the string "bad" in it. I want to replace each occurrence of "bad" with good1, good2, good3, ,, good100 and so on.

I am trying this but it is replacing all occurrences with the last number, good100

$raw = $(gc raw.txt)

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

How to accomplish this?

3 Answers 3

3

Try this:

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

This is good if the raw.txt is single line and contains the word "bad" always separed by one space " " like this: alfa bad beta bad gamma bad (and so on...)

Edit after comment:

for multiline 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
Sign up to request clarification or add additional context in comments.

11 Comments

I think there is no split method, since its throwing an error that such method doesn't exist.
Shouldn't be split() better?
Can you try this: $raw.gettype() and tell me if return [string]? String type have split() method!
There's no split method for the object array returned from Get-Content. You'll need to use foreach.
You can just cast it to a string and then use split [string] (gc raw.txt).
|
2

For such things, I generally use Regex::Replace overload that takes a Matchevaluator:

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

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

The evaluator also gets the matched groups as argument, so you can do some advanced replaces with it.

Comments

2

Here's another way, replacing just one match at a time:

$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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.