0

I need to count the number of occurrences within a single line from a string that contains backslashes and double backslashes.

I've tried using .Count, but it only counts the first instance within the line. When I try other commands, I usually get some kind of error regarding escape characters.

Here is the one line of data from the file c:\work\test.txt:

Occurrence1\\paul\dfs_app\MyFolder\QA2\testme1  Occurrence2\\paul\dfs_app\MyFolder\QA2\testme2 

And here is my code:

$inString = "\\paul\dfs_app\MyFolder\QA2"
$file = "C:\work\test.txt"
$check = Get-Content $file | Where-Object { $_.Contains($inString) }
if ($check.Count -gt 0) {
    Write-Host "Found" $check.Count.ToString().PadLeft(2, " ") "occurrences in " $file -ForegroundColor Yellow
}

It returns

Found 1 occurrences in C:\work\test.txt

but it should have found 2 occurrences.

1
  • Count does not count specific occurrences of your search string. Your Where-Object filter returns the lines that contain your search string (regardless of how often it occurs), and Count reports the number of those lines. You don't get an extra line just because one line contains your search string more than once. Commented Aug 21, 2019 at 8:46

1 Answer 1

2

You can use Select-String to count occurrences of $inString.

$out = Select-String -Path $file -Pattern ([regex]::Escape($inString)) -AllMatches
$out.Matches.Count

-Pattern without the -SimpleMatch switch turns the pattern into a regex. Using the Escape() method will automatically escape those backslashes and any other special regex character. Since it is using a regex match rather than a simple match, the matches property will contain each match found. Combining that with the AllMatches parameter, it will continue match searching after the first match on each line.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.