【问题标题】:Print line of text file if it starts with any string in array如果它以数组中的任何字符串开头,则打印文本文件的行
【发布时间】:2020-05-11 09:59:17
【问题描述】:

如果它以数组中的任何字符串开头,我正在尝试打印文本文件中的一行。

这是我的代码的 sn-p:

array = "test:", "test1:"
    if($currentline | Select-String $array) {
        Write-Output "Currentline: $currentline"
    }

如果数组变量中有任何字符串,我的代码就能够在文本文件中打印行。但我只想打印以数组变量中的字符串开头的行。

Sample of text file:
abcd-test: 123123
test: 1232
shouldnotprint: 1232

Output: 
abcd-test: 123123
test: 1232

Expected output:
test: 1232  

我已经看到一些关于stackoverflow的问题的解决方案:

array = "test:", "test1:"
    if($currentline | Select-String -Pattern "^test:") {
        Write-Output "Currentline: $currentline"
    }

但在我的情况下,我使用数组变量而不是字符串来选择内容,所以我被这部分难住了,因为它不起作用。它现在将打印任何内容。

更新: 感谢西奥的回答!这是我的代码基于 Theo 的答案供参考

array = "test:", "test1:" 
$regex = '^({0})' -f (($array |ForEach-Object { [regex]::Escape($_) }) -join '|') 
Loop here:
   if($currentline -match $regex) {
       Write-Output "Currentline: $currentline"
   }

【问题讨论】:

    标签: windows powershell select-string


    【解决方案1】:

    使用 Regex -match 运算符应该可以满足您的要求:

    $array = "test:", "test1:"
    
    # create a regex string from the array.
    # make sure all the items in the array have their special characters escaped for Regex
    $regex = '^({0})' -f (($array | ForEach-Object { [regex]::Escape($_) }) -join '|')
    # $regex will now be '^(test:|test1:)'. The '^' anchors the strings to the beginning of the line
    
    # read the file and let only lines through that match $regex
    Get-Content -Path 'D:\Test\test.txt' | Where-Object { $_ -match $regex }
    

    或者,如果要读取的文件非常大,请使用switch -Regex -File 方法,例如:

    switch -Regex -File 'D:\Test\test.txt' {
        $regex { $_ }
    }
    

    【讨论】:

    • 嗨西奥,感谢您的回答。只是为了理解您的代码,它试图遍历数组,以便我们可以转义特殊字符并附加一个“|”将每个项目连接在一起。然后,此输出将存储在 $regex 中,我们将使用“Where-Object”将当前行与生成的 regex 语句匹配。我可以知道第 3 行的“-f”选项是什么意思吗?这是否是“[regex]::Escape($_)”Powershell 等效于调用一个函数(在本例中为 Regex.Escape)?
    • @pikachu -f 是字符串格式运算符。见Get-Help about_Operators。而且,是的,[Regex]::Escape() 正在调用 .Net 的 System.Text.RegularExpressions.Regex.Escape() 函数。严格来说,[Regex] 是类名,:: 是静态成员运算符,Escape() 是成员函数。你可以称它为[System.Text.RegularExpressions.Regex]::Escape()
    猜你喜欢
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    相关资源
    最近更新 更多