Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exclude search pattern with select-string in powershell

Tags:

powershell

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

like image 819
Pedro Sales Avatar asked Aug 24 '16 14:08

Pedro Sales


People also ask

How do I select a specific string in PowerShell?

You can type `Select-String` or its alias, `sls`. Select-String is based on lines of text. By default, Select-String finds the first match in each line and, for each match, it displays the file name, line number, and all text in the line containing the match.

What does select-string do in PowerShell?

You can direct Select-String to find multiple matches per line, display text before and after the match, or display a Boolean value (True or False) that indicates whether a match is found. Select-String can display all the text matches or stop after the first match in each input file.

What PowerShell command searches for text patterns in a string?

Grep is used in Linux to search for regular expressions in text strings and files. There's no grep cmdlet in PowerShell, but the Select-String cmdlet can be used to achieve the same results.


2 Answers

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
like image 145
zawuza Avatar answered Oct 17 '22 06:10

zawuza


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"}
like image 6
Gebb Avatar answered Oct 17 '22 08:10

Gebb