简体   繁体   中英

Replacing characters in the middle of a line in a text file with PowerShell

I have the code below that I use to replace a string within a text file and it works. However; I have run into the problem where the string I want to replace is not always exactly the same, but the first few characters are. I want to find the first few characters, count 3 characters ahead, and replace that with what I want.

For example, the line I am replacing may be 123xxx , or 123aaa , etc. but the value I am replacing it with is always going to be known. How would I go about replacing the 123xxx when I won't always know what the xxx is?

((Get-Content -path $ConfPath -Raw) -replace $OldVersion,$NewVersion) | Set-Content -Path $ConfPath

As -replace uses regex, you need to escape the characters that have special meaning like in your case the dot ( any character in regex).

$OldVersion = 'jre1\.8\.0_\d{3}'  # backslash escape the dots.  \d{3} means 3 digits
$NewVersion = 'jre1.8.0_261'      # this is just a string to replace with; not regex
((Get-Content -path $ConfPath -Raw) -replace $OldVersion,$NewVersion) | Set-Content -Path $ConfPath

I researched it and figured it out using regex. The code below does exactly what I wanted to do:

((Get-Content -path $ConfPath -Raw) -replace 'jre1.8.0_...',$NewVersion) | Set-Content -Path $ConfPath

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM