Powershell script help needed - Find word beginning with something and replace it

痞子三分冷 提交于 2021-01-29 11:43:11

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!