Paragraph output using Windows findstr

35 Views Asked by At

How can I achieve the equivalent of grep -p using Windows findstr (or other Windows tools)?

In case it's not obvious, grep -p outputs the whole paragraph when it finds a match, that is all the lines between blank lines. I want to achieve the same using only functions that are part of Windows (I have a version of grep on Windows that I have no idea where I got it from, that has -p).

1

There are 1 best solutions below

5
Raky On

The built-in Windows tool findstr doesn't work exactly like grep -p does. But we can get a similar result by using findstr together with other Windows tools.

You may try this approach using powershell

$paragraph = @()
Select-String -Path "YOUR_FILE_PATH" -Pattern "YOUR_SEARCH_PATTERN" | ForEach-Object {
    if ([string]::IsNullOrWhiteSpace($_.Line)) {
        if ($paragraph.Count -gt 0) {
            $paragraph
            $paragraph = @()
        }
    } else {
        $paragraph += $_.Line
    }
}
if ($paragraph.Count -gt 0) {
    $paragraph
}