0

I need to replace a tag in an ini file for a number of files beginning with news_* using Powershell. I wrote a script to find the tag, but do not know how to replace everything from the tag to the end of the line.

for example if the ini file has:

[tag1] = A string
[tag2] = 1234567
[tag3] = Another string

And I want to replace all tag 2's with a blank string, I wrote:

$configFiles = Get-ChildItem . news* -rec
foreach ($file in $configFiles)
{
    (Get-Content $file.PSPath) |
    Foreach-Object { $_ -replace '[tag2] = ".*?"', '[tag2] = ' } |
    Set-Content $file.PSPath
}

Can you tell me what is wrong with this script?

Thanks!

1 Answer 1

4

The string you want to match doesn't have any double quotes. Also, as TheIncorrigible1 pointed out in the comments, you need to escape the square brackets, otherwise that part of your expression would be matched as a character class (any of the characters t, a, g, or 2) rather than the literal substring "[tag2]".

Change

$_ -replace '[tag2] = ".*?"', '[tag2] = '

into

$_ -replace '^(\[tag2\] = ).*', '$1'

and the problem will disappear.

$1 is a backreference to the first capturing group (the submatch between the first set of parentheses in the expression). In this case you're replacing the entire line with just the (captured) part that you want to keep.

You could also do this without capturing group/backreference by using a positive lookbehind assertion:

$_ -replace '(?<=^\[tag2\] = ).*'

Lookaround assertions are used in the match, but what they're matching doesn't become part of the value that's returned. Basically a positive lookbehind assertion means "look for something that is preceded by this subexpression".

Sign up to request clarification or add additional context in comments.

5 Comments

Don't forget he needs to escape his brackets otherwise he's searching a set.
Thanks! that did it after I escaped the brackets. What does the '$1' do? is that the equivalent of ""?
@HamletHub '$1' is equivalent to '\1' that you may recognize in other regex statements from other languages. It's a back-reference to the capture group (\[tag2\] = ) in the first replace argument.
@HamletHub btw. You don't want to use [tag1] when building an ini, just use tag1 = value otherwise you're declaring sections and syntactically wrong.
@TheIncorrigible1 Indeed. I wasn't paying attention to the square brackets. Thanks for the heads up.

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.