Matching string of pattern and size

2019-09-10 09:48发布

I want to search a text file for two strings. The output will only be printed if the first string is greater than 8 characters.

Here is the command I am trying to run:

Get-Content -Path .\std_server*.out | Select-String '((if "cpu=" -gt 8)|application=")' | out-File  -width 1024 .\test.txt

So I want to search file std_server*.out for both values CPU and APPLICATION, but I only want to print these values if the value for CPU is greater than 8 characters.

How do I do that?

Currently, I have a basic version that works with '(cpu=|application=")', however that prints out all values of CPU, and I only want the application to be printed out when CPU is an unreasonably high value (CPU > 8).

Thanks in advance.

2条回答
对你真心纯属浪费
2楼-- · 2019-09-10 10:04

If they're on their own lines could use something like

Get-Content -Path .\std_server*.out | ?{($_.StartsWith("CPU=") -And $_.Length -gt 12) -Or $_.StartsWith("Application=")} | out-File  -width 1024 .\test.txt

Or you could check for an end character (semicolon for example) like

Get-Content -Path .\std_server*.out | ?{(($_.StartsWith("CPU=") -And $_.Length -gt 12) -Or $_.StartsWith("Application=")) -And $_.EndsWith(";")} | out-File  -width 1024 .\test.txt

Or just use a regular expression, like

Get-Content -Path .\std_server*.out | Select-String '^(cpu=\d{8,}|application=\d*)$' | out-File  -width 1024 .\test.txt

if they're on their own lines, or

Get-Content -Path .\std_server*.out | Select-String '(cpu=\d{8,}|application=\d*);' | out-File  -width 1024 .\test.txt

if they're delimited by a character (in this case ';').

查看更多
该账号已被封号
3楼-- · 2019-09-10 10:14

That nested logic with the if won't work as you have seen. You need a quantifier for the characters that match after cpu= in order to define the conditional match there. You could measure the match with some post processing as well but it might create more headache since you have to work around the application=" matches as well.

Presumably your file will have those string at the start of the line and nothing else follows them? To ensure the correct matches it would be a good idea to use anchors.

Also you might as well use Export-CSV with the right properties since Select-String return matches objects.

$pattern = '^(cpu=.{8,}|application=".*)$'
Get-Content -Path .\std_server*.out | 
        Select-string -Path  c:\temp\text.txt -Pattern $pattern | 
        Select-Object Path,LineNumber,Line | 
        Export-CSV -NoTypeInformation .\test.txt

cpu=.{8,} will match "cpu=" literally and then at least 8 characters have to follow it for a match. We use anchors to ensure from the start to the end of the matches is exactly what we want and nothing more.

You first and last sentences conflict for me but it is possible that the whole match is supposed to be 8 characters so perhaps you just want the number 4.

查看更多
登录 后发表回答