问题
I'm trying to change a string within a file to a string with timestamp on the end but cant work out how to find the initial string using a regex in Powershell
(Get-Content sw.js).replace('SW-cache-v.*', 'SW-cache-v'+$(Get-Date -format "s")) | Set-Content sw.js
the SW-cache-v.*
isn't working for me, I'm just not picking up the string in order to replace it.
Any thoughts on how to do it?
回答1:
In PowerShell, the -replace
comparison operator uses regex matching with string replacement.
$Replace = "SW-cache-v{0}" -f (Get-Date -format s)
(Get-Content sw.js) -replace 'SW-cache-v.*',$Replace | Set-Content sw.js
Keep in mind that .*
greedily matches all characters until the end of the current line here. For example, if you wanted to only match up until but excluding the next "
character, you could use a negated character class [^]
:
(Get-Content sw.js) -replace 'SW-cache-v[^"]*',$Replace | Set-Content sw.js
The String.Replace .NET method does a literal string replacement (case-sensitively).
# Wildcards and regex are not allowed with .Replace()
'SW-cache-v extra chars'.Replace('SW-cache-v.*','newstring')
SW-cache-v extra chars
# Literal matching is used by .Replace()
'SW-cache-v.*'.Replace('SW-cache-v.*','newstring')
newstring
-replace
defaults to case-insensitive matching. The -creplace
operator respects the case.
来源:https://stackoverflow.com/questions/60933000/powershell-script-help-needed-find-word-beginning-with-something-and-replace-i