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