2

I have logs in this format. I'm looking to get logs only that has count more than 5000.

Matching pattern should be Count [value greater than 5000]

INFO 56783 Count [5987] 
INFO 67988 Count [4986] 
INFO 27679 Count [9865] 

In the above example, the output should be only

 INFO 56783 Count [5987] 

I'm using in the following format

sudo cat <path to log> | grep 'Count [5[0-9][0-9][0-9]]'

Any ideas what is missing here

1
  • 1
    Just one correction. Output should contain 9865 also as it is > 5000 Commented Mar 3, 2022 at 15:36

2 Answers 2

2

You may use this grep:

grep -E 'Count \[[5-9][0-9]{3,}\]' file

INFO Count [5987]
INFO Count [9865]

Here regex pattern is \[[5-9][0-9]{3,}\] that matches a:

  • \[: Match opening [
  • [5-9]: Match digits between 5 to 9
  • [0-9]{3,}: Match 3 or more digits
  • \]: Match closing ]

This will match 5000 or an integer greater than 5000 inside [...].

However, you should be using awk for this job to get most flexibility:

awk '$2 == "Count" && gsub(/[][]/, "", $3) && $3+0 > 5000' file

INFO Count 5987
INFO Count 9865
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks Anubhava, can you please help me in understanding [[5-9][0-9]{3,}]
I have added regex details in answer.
Perfect explanation. Cheers!
Quick question, if I want to pull values ONLY that are less than 5000?
Using grep for values < 5000, use grep -E 'Count \[([0-9]|[1-9][0-9]{1,2}|[1-4][0-9]{3})\]' file
|
1

You can use

awk -F'[][]' '/Count \[[0-9]+]/ && $2 > 5000' file

The field separator matches ] or [ and /Count \[[0-9]+]/ && $2 > 5000 only outputs lines that contain Count [<number>] and where Field 2 is more than 5K.

See the online demo:

#!/bin/bash
s='INFO Count [5987] 
INFO Count [4986] 
INFO Count [9865] '
awk -F'[][]' '/Count \[[0-9]+]/ && $2 > 5000' <<< "$s"

Output:

INFO Count [5987] 
INFO Count [9865]

5 Comments

Thanks, but it should match the exact string as "Count [5987]". Can we do it with grep?
@Syed I added the obligatory Count [number] part. With grep, you can use grep '\[[5-9][0-9]\{3,\}]' file.
@Syed Yes, and this works for that edit, too.
Quick question, if I want to pull values ONLY that are less than 5000? by using grep
@Syed grep -E 'Count \[[1-4]?[0-9]{1,3}]' file / grep 'Count \[[1-4]\{0,1\}[0-9]\{1,3\}]' file, see regex101.com/r/gVh7tp/1

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.