我想使用另一个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 –