Powershell用给定的模式替换线条

时间:2017-02-11 13:02:44

标签: regex powershell

背景

我正在尝试读取配置文件并将其放在字符串变量中以供进一步使用。现在我已经成功删除了换行符,这非常简单。但是,我在删除注释时遇到了一些麻烦(以#开头的行)。

到目前为止我有什么

$var = (Get-Content $HOME/path/to/config.txt -Raw).Replace("`r`n","")

我尝试了什么

很多事情都是

$var = (Get-Content $HOME/path/to/config.txt -Raw).Replace("#.*?`r`n","").Replace("`r`n","")

( .Replace("(?<=#).*?(?=`r`n)","") , .Replace('^[^#].*?`r`n','') etc)

我发现的很多资源已经处理过如何迭代地从文件中读取并写回到它或新文件,但我需要的是结果保留在变量中而原始文件不是以任何方式改变(如果可能的话,我宁愿避免使用临时文件甚至变量)。我认为Replace的输入缺少一些基本的东西。 (当您使用ConvertFrom-Csv Using Import-CSV in Powershell, ignoring commented lines时,也会发现此半相关内容。)

示例输入:

text;
weird text;
other-sort-of-text;
#commented out possibility;
more-input/with-comment;#comment

示例输出:

text;weird text;other-sort-of-text;more-input/with-comment;

其他信息:

我将在当前版本的Windows 10上运行此功能,本地现在我似乎有pwershell版本5.1.14393.693

3 个答案:

答案 0 :(得分:1)

以分号分割字符串,删除以#开头的元素,然后将结果连接回字符串。

((Get-Content $HOME/path/to/config.txt -Raw).Replace("`r`n","") -split ';' |
    Where-Object { $_.Trim() -notlike '#*' }) -join ';'

答案 1 :(得分:0)

这可能与其他一些回复相同,但这是我将如何做到的:

$Data = Get-Content $HOME/path/to/config.txt -Raw
(($Data -split(';')).replace("`r`n",'') | Where-Object { $_ -notlike '^#*' }) -join(';')

无论如何你要这样做,记住r n需要扩展,所以它必须用双引号括起来,不像你的其他字符。

答案 2 :(得分:0)

#############solution 1 with convertfrom-string####################

#short version
(gc "$HOME/path/to/config.txt" | ? {$_ -notlike "#*"} |  cfs -D ";").P1 -join ";"

#verbose version
(Get-Content "$HOME/path/to/config.txt"  | where {$_ -notlike "#*"} |  ConvertFrom-String -Delimiter ";").P1 -join ";"


#############Solution 2 with convertfrom-csv#######################

(Get-Content "C:\temp\test\config.txt"  | where {$_ -notlike "#*"} |  ConvertFrom-csv -Delimiter ";" -Header "P1").P1 -join ";"


#############Solution 3 with split #######################

(Get-Content "C:\temp\test\config.txt"  | where {$_ -notlike "#*"} |  %{$_.Split(';')[0]}) -join ";"