Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

What is the mos easy/comfortable way to use Powershells built-in functions to emulate grep like behaviour?

In scripts I use something like this

dir "*.filter" | foreach-object{
    $actfile = $_
    $readerrorfile = [System.IO.Path]::GetTempFileName()
    $found = $false
    $content = Get-Content $actfile 2> $readerrorfile
    $readerror = Get-Content $readerrorfile
    if($readerror -match "Error"){
        echo "Error while reading from file $actfile"
        echo $readerror
        del $readerrorfile
        Write-Host "stopping execution"
        exit
    }else{
        del $readerrorfile
        if($content -match "keyword|regex"){
            echo "found in $actfile"
            $found = true;
        }
    }
}

I fairly sure there is an easier/shorter version for that, maybe a one-liner. So, what is the best way to it the grep way?

share|improve this question

2 Answers 2

up vote 9 down vote accepted

I normally do something like:

dir *.txt | select-string "keyword|regex"

For a matching file, this shows me the name of the file, the line number and the contents of the line. This is also pipeline-friendly. I suggest that you have a look at Select-string by using:

help Select-String -Detailed
share|improve this answer
    
thx, that's exactly what I wanted –  mbx Apr 7 '11 at 15:41
    
although this mostly works, if the line is too long the it's wrapped after 120 characters even when piped to file –  mbx Jun 9 '11 at 11:15
    
You won't have an issue with wrapping if you pipe Select-String to Set-Content or Add-Content –  Rynant Sep 16 '11 at 17:58

I find this to be a better alternative than piping dir:

findstr "keyword|regex" *.txt

This doesn't have that wrapping problem.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.