将正则表达式添加到文本文件中的行(如果尚不存在)

时间:2019-04-02 19:27:07

标签: regex powershell if-statement

我正在尝试将正则表达式添加到文本文件中每行的开头(如果尚不存在)。输入是URL列表,而正则表达式是协议列表。

我尝试了不同的if / else循环和cmdlet(例如add-content / set-content)来添加正则表达式,但是每次逻辑都是关闭的。目前我拥有的是:

$content = Get-Content "C:\path\to\file\test.txt"
$pattern = "[regex]::^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/|tcp:\/\/|ssl:\/\/)" 
ForEach-Object { 
    if ($content -match $pattern) 
        {$content}
    else {
        {foreach($_ in $content) {"^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/|tcp:\/\/|ssl:\/\/)" + $_ }}
          }
 } | Out-File "C:\path\to\file\test.txt"

我希望输出为

^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/|tcp:\/\/|ssl:\/\/)netflix.com
^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/|tcp:\/\/|ssl:\/\/)google.com
^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/|tcp:\/\/|ssl:\/\/)yahoo.com

但实际输出是

"^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/|tcp:\/\/|ssl:\/\/)" + $_

1 个答案:

答案 0 :(得分:0)

我想我明白了,但是我不得不猜测输入中的某些内容。

这就是我用来输入的内容

google.com
yahoo.com
netflix.com

这是我使用的修改后的Powershell。如果输入中的一行不匹配,则在该行的开头具有模式,它将用包括模式的替换文本替换当前字符串。然后,它在输入中查找原始字符串的索引并替换它。最后,它将所有内容写回到原始文件中。

$content = Get-Content "C:\path\to\file\test.txt"
$pattern = "^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/|tcp:\/\/|ssl:\/\/)" 

$content | ForEach-Object { 
    if ($_ -notlike $pattern +"*") {
        #Write-Host "^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/|tcp:\/\/|ssl:\/\/)" + $_ 
        $replaceText = $_ -replace "^$_$", "$pattern$_"  
        $content[($content.IndexOf("$($content -like "$_")"))] = $replaceText
    }
}

$content | Set-Content "C:\path\to\file\test.txt"

更新文件的输出为:

^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/|tcp:\/\/|ssl:\/\/)google.com
^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/|tcp:\/\/|ssl:\/\/)yahoo.com
^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/|tcp:\/\/|ssl:\/\/)netflix.com