Home > Software engineering >  How do I add 1 to a variable each time it replaces a specific string
How do I add 1 to a variable each time it replaces a specific string

Time:02-10

What I am trying to do is add 1 to $b each time it replaces the word hello with modal$b so it should look like modal1, modal2 etc.

 $a=1
$b=1
$original_file = 'C:\Users\me\Desktop\2.txt'
$destination_file =  'C:\Users\me\Desktop\4.txt'
do { 
(Get-Content $original_file)  | ForEach-Object  {
  $_  -replace "hello", "modal$b"` 

    } | add-Content $destination_file

    $a  
}
until ($a -gt 1)

Any help would be greatly appreciated! thanks, Sarash

CodePudding user response:

You could do it with just a ForEach-Object loop, there doesn't seem to be a need for the Do loop. Following what you already have, you can increase your variable like below.

$original_file = 'C:\Users\me\Desktop\2.txt'
$destination_file = 'C:\Users\me\Desktop\4.txt'
$b = 0
Get-Content $original_file | ForEach-Object {
    $_ -replace 'hello', "modal$(($b  ))"
} | Out-File $destination_file

The following would work too, using a Regex.Replace with a Script Block, this example would require to use the -Raw switch on Get-Content. It's important to note that using this method, the pattern is case sensitive (i.e.: 'Hello' will not match 'hello'), if you want it to be case-insensitive you could use the (?i) flag: '(?i)hello'.

[ref]$ref = 0
[regex]::Replace((Get-Content $original_file -Raw), 'hello', {
    "modal$(($ref.Value  ))"
}) | Out-File $destination_file

Replacement with a script block was implemented in PowerShell 6 (Core), thanks Mathias R. Jessen for the hard work :)

Above example, if you have PS Core, would be replaced by:

[ref]$ref = 0
(Get-Content $original_file -Raw) -replace 'hello', {
    "modal$(($ref.Value  ))"
} | Out-File $destination_file

And there wouldn't be a need for the (?i) flag since -replace is already case-insensitive.

  • Related