26

I'm using select string to search a file for errors. Is it possible to exclude search patterns as with grep. Ex:

grep ERR* | grep -v "ERR-10"

select-string -path logerror.txt -pattern "ERR"

logerror.txt

OK
ERR-10
OK
OK
ERR-20
OK
OK
ERR-10
ERR-00

I want to get all the ERR lines, but not the ERR-00 and ERR-10

8
  • do you have a single ERR item per line? Commented Aug 24, 2016 at 15:32
  • Use -Exclude 'ERR-10' Commented Aug 24, 2016 at 15:34
  • I don't have a ERR per line Commented Aug 24, 2016 at 15:43
  • -(not)match should work, you might wanna have a look at the help and/or post a sample of your file Commented Aug 24, 2016 at 15:46
  • 3
    @Hitesh The -Exclude is for the -Path only, not the pattern Commented Aug 25, 2016 at 10:35

2 Answers 2

36

I use "-NotMatch" parameter for this

PS C:\>Get-Content .\some.txt
1
2
3
4
5
PS C:\>Get-Content .\some.txt | Select-String -Pattern "3" -NotMatch    
1
2
4
5

For your case the answer is:

Get-Content .\logerror.txt | Select-String -Pattern "ERR*" | Select-String -Pattern "ERR-[01]0" -NotMatch
Sign up to request clarification or add additional context in comments.

Comments

8

I guess you can use Where-Object here.

Write-Output @"
OK
ERR-10
OK
OK
ERR-20
OK
OK
ERR-10
ERR-00
"@ > "C:\temp\log.txt"

# Option 1.
Get-Content "C:\temp\log.txt" | Where-Object { $_ -Match "ERR*"} | Where-Object { $_ -NotMatch "ERR-[01]0"}

# Option 2.
Get-Content "C:\temp\log.txt" | Where-Object { $_ -Match "ERR*" -and $_ -NotMatch "ERR-[01]0"}

5 Comments

Thank you for you answer. I understand what you want to do, but this is just an example. If I have more and more complex error codes (like I do), this doesn't work: Example:ERR-201,ERR-422;ERR-240. I just needed a way to filter the erros, because some are really erros and others are just informations.
@PedroSales, You modify the regexp then. The code I've shown is the equivalent of grep -v "ERR-[01]0", i.e. you use a regexp to exclude lines from the output. I guess you already know how to emulate grep without the -v argument.
With grep, I just pipe another grep -v with another error code
Exactly. Ok, I will modify my answer to match your combination of greps.
Thank you so much for your help. I've een around with this for a couple of days now.

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.