Powershell Get-Content -> 参数“-replace”
Powershell Get-Content -> Parameter "-replace"
嗨!
- “-replace”参数是否绑定到cmdlet“Get-Content”?通过谷歌搜索,我在许多不同的上下文中找到了它
- 为什么 -replace Parameter 没有出现在官方文档中? Get-Content Microsoft
问题:
文本近似如下:
olor sit amet, consetetur sadipscing elitr, sed diam nonumy
LoremIpsum-648648sdfsd
我想通过正则表达式将子字符串从“LoremIpsum-xxx”替换为“Loremipsum”
这是我的第一次尝试:
(Get-Content "C:\File.cmd") -replace "[regex]::matches("LoremIpsum-(.*?)")" | Out-File -encoding ASCII C:\File.cmd
-replace
不是 Get-Content
参数,它是一个运算符,允许使用正则表达式查找指定的模式,然后删除匹配的文本或将其替换为另一个。
对于你的情况,你可以使用
(Get-Content "C:\File.cmd") -replace '(?<=\bLoremIpsum)-\w+' | Out-File -encoding ASCII C:\File.cmd
(?<=\bLoremIpsum)-\w+
正则表达式匹配连字符 (-
) 和一个或多个单词字符 (\w+
),它们紧接在 LoremIpsum
之前作为一个完整的单词(\b
是一个单词边界)。
注意 如果您想删除 [=17= 之后的任何一个或多个 non-whitespace 个字符,您可以将 \w+
替换为 \S+
].
或者,您可以使用
(Get-Content "C:\File.cmd") -replace '\b(LoremIpsum)-\w+', '' | Out-File -encoding ASCII C:\File.cmd
这里,LoremIpsum
被捕获到一个捕获组中(ID为1,因为它是正则表达式中的第一个捕获组),现在替换为
,替换反向引用指的是第 1 组值。
参见regex demo #1 and this regex demo。
嗨!
- “-replace”参数是否绑定到cmdlet“Get-Content”?通过谷歌搜索,我在许多不同的上下文中找到了它
- 为什么 -replace Parameter 没有出现在官方文档中? Get-Content Microsoft
问题:
文本近似如下:olor sit amet, consetetur sadipscing elitr, sed diam nonumy LoremIpsum-648648sdfsd
我想通过正则表达式将子字符串从“LoremIpsum-xxx”替换为“Loremipsum”
这是我的第一次尝试:
(Get-Content "C:\File.cmd") -replace "[regex]::matches("LoremIpsum-(.*?)")" | Out-File -encoding ASCII C:\File.cmd
-replace
不是 Get-Content
参数,它是一个运算符,允许使用正则表达式查找指定的模式,然后删除匹配的文本或将其替换为另一个。
对于你的情况,你可以使用
(Get-Content "C:\File.cmd") -replace '(?<=\bLoremIpsum)-\w+' | Out-File -encoding ASCII C:\File.cmd
(?<=\bLoremIpsum)-\w+
正则表达式匹配连字符 (-
) 和一个或多个单词字符 (\w+
),它们紧接在 LoremIpsum
之前作为一个完整的单词(\b
是一个单词边界)。
注意 如果您想删除 [=17= 之后的任何一个或多个 non-whitespace 个字符,您可以将 \w+
替换为 \S+
].
或者,您可以使用
(Get-Content "C:\File.cmd") -replace '\b(LoremIpsum)-\w+', '' | Out-File -encoding ASCII C:\File.cmd
这里,LoremIpsum
被捕获到一个捕获组中(ID为1,因为它是正则表达式中的第一个捕获组),现在替换为,替换反向引用指的是第 1 组值。
参见regex demo #1 and this regex demo。