Powershell - replace text after wildcard, with nothing?
I am using a Powershell command in a Windows batch file to search for a text string like this: foo=1
(where 1
could be anything)
I know .*?
works as a wildcard in Powershell. The below snippet isn't the full command, I have only put the relevant part.
I am trying to replace the whole line foo=1
with nothing, using the Powershell wildcard .*?
for the 1
like this:
-replace 'foo=.*?', ''
The problem is, instead of being left with a blank line, I am still left with the trailing =1
I don't know why the wildcard is not being replaced with nothing as per the command in the code box above.
Thanks in advance to any answers that shed some light on it.
Solution 1:
.?*
is not "a wildcard" in PowerShell.
The -Replace
operator in PowerShell doesn't use wildcard matching, it uses regular expressions.
In regular expressions, .
will match any single character except a line break. ?
and *
, as well as +
are quantifiers used in conjuction with .
or other, more specific, matching characters. So that:
-
'.?'
matches none or one character -
'.*'
matches zero or more characters -
'.+'
matches one or more characters
Wildcards in PowerShell are used by the -Like
and -notLIke
operators, as well as being used to easily specify multiple paths. In additon to the *
and ?
familiar to most, brackets ( [
& ]
) can be used to define a character range or enumeration. This is why paths with bracket characters in the name require the use of the -LiteralPath
parameter.
So, for your question/example, you need a simple regular expression. But "1
could be anything" leaves several options:
- Always a single character
-replace 'foo=.'
- One or more characters up to the end of the string.
-replace 'foo=.+$'
- One or more characters until space (or other known delimiter)
-replace 'foo=.+\ ' # space
-replace 'foo=.+,' # comma
Solution 2:
I kept fiddling and worked it out:
-replace 'foo=.*?.*', ''
Adding the extra .*
after the original wildcard made it work.
OK now I have hours and hours of work to do ;)