[英]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.
我想找到前几个字符,提前数 3 个字符,然后用我想要的替换它。
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.例如,我要替换的行可能是
123xxx
或123aaa
等,但我要替换它的值始终是已知的。 How would I go about replacing the 123xxx
when I won't always know what the xxx
is?当我不总是知道
xxx
是什么时,我将如何更换123xxx
?
((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).由于
-replace
使用正则表达式,因此您需要转义具有特殊含义的字符,例如在您的情况下是点(正则表达式中的任何字符)。
$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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.