7

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?

2
  • Your code works perfect on PS2.0 and PS3.0 Commented Mar 8, 2013 at 9:25
  • Have you tried using XML parsing? Don't know if that's applicable, but if you know in what element of the XML you need to replace your string, that may be "cleaner" Commented Mar 8, 2013 at 10:15

2 Answers 2

15

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

3 Comments

Thanks. But doesn't -replace and pipeline results in string replacement? If I want to use original way how to change $_?
I also tried not using regex but fixed string and it works. Such as below (Get-Content "test1.xml") | ForEach-Object {$_ -replace 'name-1a2b3c4d', "name-6a5e4r3h"} | Set-Content "test2.xml"
@user1201530 The first parameter for -replace is always a regex. When you use 'name-1a2b3c4d' you are omiting the ^ (at the start of the line) and the $ (at the end of the line). Maybe in your original file name-1a2b3c4d doesn't match ^.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.