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
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.
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.
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.
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
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With