Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace each occurrence of string in a file dynamically

Tags:

powershell

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?

like image 219
Animesh Avatar asked Mar 21 '26 23:03

Animesh


1 Answers

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
like image 193
CB. Avatar answered Mar 24 '26 22:03

CB.