user1218240
user1218240

Reputation: 195

Find and replace at powershell

My textfile looks like this:

-------------------
Set PRGVER="V1.0.12"
Set PRGDIR=C:\PRGSTD\oif_mes\OIFplus
Set PRGEXE=OIFplus.bat
Set PRGTXT=OIFplus

echo %PRGTXT%, %PRGVER%
start "%PRGTXT%" /D%PRGDIR%\%PRGVER%\ %PRGDIR%\%PRGVER%\%PRGEXE%
----------------------

What I wan't to do, edit this file, only change Set PRGVER="V1.0.12" to a new number, like this Set PRGVER=V1.0.13".
When is start the PS Script, I don't know the whole string, the number between "".
I only know, find string variable: Set PRGVER="".

How can I replace only the first value between ""?

Upvotes: 1

Views: 3079

Answers (4)

Dmitry Aleksandrov
Dmitry Aleksandrov

Reputation: 710

Something like this;

$srt = <your text>
$r = $str -replace "PRGVER=`".*`"", "PRGVER=`"your_replace`""

Upvotes: 2

Akim
Akim

Reputation: 8689

Following PoSH will replace PRGVER value:

$newValue = "v123.456.789"
gc D:\temp\text | % { $_ -ireplace '(Set PRGVER=)\"([^"]*)\"', ('$1"' + $newValue + '"') };

Upvotes: 0

Shay Levy
Shay Levy

Reputation: 126932

The following should do it. It finds the a line that starts with 'Set PRGVER="V', followed by any number of digits, then a dot, any number of digits, a dot, any number of digits, and ends with '"'. When found, the line is replaced with 'Set PRGVER="V1.0.13"' and the result is saved back to the file.

(Get-Content file.txt) -replace '^Set PRGVER="V\d+\.\d+.\d+"$','Set PRGVER="V1.0.13"' | Out-File file.txt

Upvotes: 0

Related Questions