2016-12-01 113 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