我想使用另一個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
成功匹配行的末尾?
也許複製整個文件一行一行地斷言與第一個標誌#?如果有,只需跳過該行並繼續下一行。 – pizycki
\ r \ n僅用於Windows默認文件編碼。例如,如果你在linux上創建了你的文件,那麼你不會每次都有\ r –