2016-12-01 116 views
1

我想使用另一个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 '#.*\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 

我也试着写只是\n,即使我敢肯定,我的文件是CRLF。而且我也试图在开始时加入\n\r\n。这些根本不起作用,但他们也没有错误。

测试文件:

commented.ps1:

#This is a comment 
$var = 'this is a variable' 
# This is another comment 
$var2 = 'this is another variable' 

预期uncommented.ps1:

​​

我只是不明白为什么\r\n不匹配行尾。任何帮助,高度赞赏。我想问题是:

如何在PowerShell中使用Get-Content -replace成功匹配行的末尾?

+0

也许复制整个文件一行一行地断言与第一个标志#?如果有,只需跳过该行并继续下一行。 – pizycki

+0

\ r \ n仅用于Windows默认文件编码。例如,如果你在linux上创建了你的文件,那么你不会每次都有\ r –

回答

5

而不是使用-replace,你可以使用简单的Where-Object没有注释符号(#),正则表达式以及是非常简单的过滤线,^#手段匹配在该行的开头任何#字符,请参阅:http://www.regular-expressions.info/anchors.html

(Get-Content commented.ps1) | Where-Object {$_ -notmatch '^#'} | Set-Content uncommented.ps1 
+1

是的,我也考虑过这个问题。好的! –

+0

这个工作,所以我想这是正确的答案,但你能给出一些解释为什么?这将使它更好的答案。如果你也碰巧知道为什么\ r \ n不起作用,那将是完美的。 – Andrei

+1

更新了解释的答案... – Avshalom