【问题标题】:Search multiline text in a file using powershell使用 powershell 在文件中搜索多行文本
【发布时间】:2018-06-27 10:53:35
【问题描述】:

我不是 PowerShell 专家。我正在尝试在文件中搜索多行字符串,但没有得到想要的结果。

这是我的代码:

$search_string = @("This is the first line`nThis is the second line`nThis is the third line")
$file_path = "log.txt"
$ret_string = @(Get-Content -Path $file_path | Where-Object{$_.Contains($search_string)}).Count
Write-Host $ret_string

$ret_string 设置为0,尽管"log.txt" 包含与$search_string 完全相同的内容。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    这里有几个问题:

    1. 您正在搜索行数组,而不是包含换行符的字符串
    2. 如果您使用的是 Windows,则需要使用 \r\n 作为新行
    3. .Contains 函数将返回一个布尔值,因此无法帮助您检索计数
    4. 您的 $search_string 不必是数组

    您可以使用-Raw 参数以字符串形式获取整个文件内容。您最好使用正则表达式在此处搜索。试试:

    $search_string = "This is the first line`r`nThis is the second line`r`nThis is the third line"
    $file_path = "log.txt"
    $ret_string = (Get-Content -raw -Path $file_path | Select-String $search_string -AllMatches | % { $_.matches}).count
    

    这将返回文件中出现的所有$search_string 的计数

    【讨论】:

      【解决方案2】:

      Get-Content 返回一个字符串数组(每行一个),每个字符串在Where-Object 条件中单独检查。您需要将文件作为单个字符串读取才能进行检查:

      Get-Content $file_path | Out-String | Where-Object { ... }
      

      在 PowerShell v3 或更新版本上,cmdlet 有一个用于读取原始文件的参数:

      Get-Content $file_path -Raw | Where-Object { ... }
      

      但是请注意,您可能需要调整您的条件以检查`r`n 而不仅仅是`n,尤其是第一种方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-30
        • 1970-01-01
        • 2022-11-28
        • 2019-10-24
        • 1970-01-01
        相关资源
        最近更新 更多