使用 powershell 搜索文件中的多行文本

San*_*Jha 1 powershell

我不是 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
Run Code Online (Sandbox Code Playgroud)

$ret_string设置为0虽然"log.txt"包含与 完全相同的内容$search_string

arc*_*444 5

这里有几个问题:

  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
Run Code Online (Sandbox Code Playgroud)

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