0

I am trying to find a way to replace the same string with different values in a text file using powershell. The word is the same with special characters (e.g "[Placeholder]"). This is for a .json file that looks something similar to this.

Line1: 
Line2:
Line3: [Placeholder]
Line4:  [Placeholder]

The idea is to change the string [Placeholder] on line 3 with the version and line 4 with the current date. When i try to do this with the following code it automatically replaces both [Placeholder]'s with the version and i am struggling to find a way to have line 3 be the version and 4 the date

$currentVersion = "v.1.2.3.4"
$currentDate =  "08/08/2021"
$original_file = 'C:\Users\samue\Desktop\D\V1\hehehehe.txt'
(Get-Content $original_file) | Foreach-Object {
    $_ -replace ([regex]::Escape('[Placeholder]')), $currentVersion `
      -replace ([regex]::Escape('[Placeholder]')), $currentDate
    } | Set-Content $original_file
 

As you can see it will replace all [placeholder]'s with $currentVersion because that is the first thing it finds but I need some help on maybe how to use regex to match and then replace the word

Line1: 
Line2:
Line3: v.1.2.3.4
Line4:  v.1.2.3.4
  • 2
    If he original file is in JSON format, could you not just use [ConvertFrom-Json](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertfrom-json?view=powershell-7.1) to get it in object format, update the appropriate properties, then save with [ConvertTo-Json](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertto-json?view=powershell-7.1)? – boxdog Aug 10 '21 at 08:55
  • @boxdog Thanks this solved my issue ! leaving the answer below. PS: the only thing that i might need to do is to not use two if statements for this and use -and but i need to check on that (very new to PS!). – Samuel Van Bladel Aug 10 '21 at 09:40

2 Answers2

0

Thanks to @boxdog for mentioning ConvertFrom-Json With that I found the following Stack overflow post :

$currentDate =  "08/08/2021"
$a = Get-Content 'C:\Users\samue\Desktop\D\V1\hehehehe.json' -raw | ConvertFrom-Json
$a.update | % {if($_.Version -eq '[Placeholder]'){$_.Version=$currentVersion} }
$a.update | % {if($_.date -eq '[Placeholder]'){$_.date=$currentDate}}
$a | ConvertTo-Json -depth 32| set-content 'C:\Users\samue\Desktop\D\V1\hehehehe.json'

Only thing would be to not use 2 if statements but i have to learn a bit more PS to do that !

0

You can use "capture" property of -replace:

> $str = "Line3: [Placeholder]`nLine4:  [Placeholder]"

> $str -replace '(Line[0-9]+: )\[Placeholder\]', '$1 v.1.2.3.4'                                         
Line3:  v.1.2.3.4
Line4:  [Placeholder]

> $str -replace '(Line[0-9]+:  )\[Placeholder\]', '$1 v.1.2.3.4'
Line3: [Placeholder]
Line4:   v.1.2.3.4

The content in parenthesis is captured and inserted via $1.

C. Aknesil
  • 186
  • 3