我想使用另一个PowerShell脚本删除powershell脚本中的所有注释行.我希望这很容易,但显然不是.这是我尝试过的东西,显然没有用:
(Get-Content commented.ps1) -replace '^#.*$', '' | Set-Content uncommented.ps1
(Get-Content commented.ps1) -replace '#.*$', '' | Set-Content uncommented.ps1
Run Code Online (Sandbox Code Playgroud)
这些都有效,但行尾仍然存在,所以现在我有一些空行而不是注释,这不是我想要的.
(Get-Content commented.ps1) -replace '#.*\r\n', '' | Set-Content uncommented.ps1
(Get-Content commented.ps1) -replace '^#.*\r\n$', '' | Set-Content uncommented.ps1
(Get-Content commented.ps1) -replace '#.*\r\n$', '' | Set-Content uncommented.ps1
Run Code Online (Sandbox Code Playgroud)
我也试着写\n,即使我确定我的文件是CRLF.而且我也尝试过\n或者\r\n在开始时.这些根本不起作用,但它们也没有错误.
测试文件:
评论.ps1:
#This is a comment
$var = 'this is a variable'
# This is another comment
$var2 = 'this is another variable'
Run Code Online (Sandbox Code Playgroud)
预期uncommented.ps1:
$var = 'this is a variable'
$var2 = 'this is another variable'
Run Code Online (Sandbox Code Playgroud)
我根本就不明白为什么\r\n不匹配行尾.任何帮助都非常感谢.我想问题是:
如何在powershell中使用成功匹配行尾Get-Content -replace?
而不是使用-replace你可以使用简单Where-Object的过滤行而没有注释符号(#),正则表达式也很简单,^#意味着匹配#行开头的任何字符,请参阅:http://www.regular-expressions.info/ anchors.html
(Get-Content commented.ps1) | Where-Object {$_ -notmatch '^#'} | Set-Content uncommented.ps1
Run Code Online (Sandbox Code Playgroud)