Sandhya Jha
Sandhya Jha

Reputation: 376

Search multiline text in a file using powershell

I am not an expert at PowerShell. I am trying to search for a multi-line string in a file, but I don't get the desired result.

Here is my code:

$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 is set to 0 although "log.txt" contains exactly the same content as $search_string.

Upvotes: 1

Views: 3284

Answers (2)

arco444
arco444

Reputation: 22821

A few problems here:

  1. You are searching an array of lines, not a string containing line breaks
  2. If you're using Windows you need to use \r\n as a new line
  3. The .Contains function will return a boolean value, so won't help you retrieve a count
  4. Your $search_string does not need to be an array

You can use the -Raw parameter to get the entire file contents as a string. You're also better off using a regular expression to search here. Try:

$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

This will return a count of all the occurrences of $search_string in the file

Upvotes: 5

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200213

Get-Content returns an array of strings (one per line), each of which is checked separately in your Where-Object condition. You need to read the file as a single string for your check to work:

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

On PowerShell v3 or newer the cmdlet has a parameter for reading the raw file:

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

Note, however, that you may need to adjust your condition to check for `r`n rather than just `n, particularly with the first approach.

Upvotes: 4

Related Questions