Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use powershell ForEach-Object to match and replace string with regex

I use the below pipeline to read a file and replace a line in it and save it to another file, but found that the string in target file is not replaced, it's still the old one.

original line is : name-1a2b3c4d

new line should be: name-6a5e4r3h

(Get-Content "test1.xml") | ForEach-Object {$_ -replace '^name-.*$', "name-6a5e4r3h"} | Set-Content "test2.xml"

Anything missing there?

like image 346
user1201530 Avatar asked Mar 08 '13 09:03

user1201530


2 Answers

One thing you're missing is that the -replace operator works just fine on an array, which means you don't need that foreach-object loop at all:

(Get-Content "test1.xml") -replace '^name-.*$', 'name-6a5e4r3h' | Set-Content test2.xml
like image 160
mjolinor Avatar answered Sep 19 '22 12:09

mjolinor


You're not changing the $_ variable.

You might try:

$lines = Get-Content $file
$len = $lines.count
for($i=0;$i-lt$len;$i++){
    $lines[$i] = $lines[$i] -replace $bad, $good
}
$lines > $outfile
like image 42
E.V.I.L. Avatar answered Sep 21 '22 12:09

E.V.I.L.