Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep to extract the word matching the given pattern

Tags:

shell

unix

I have a log file with entries like

INFO 2013-08-16 13:46:48,660 Index=abc:12 insertTotal=11  
INFO 2013-08-16 13:46:48,660 Index=abcd:12 insertTotal=11  
INFO 2013-08-16 13:46:48,660 Index=def:134 insertTotal=11  
INFO 2013-08-16 13:46:48,660 Index=abkfe insertTotal=11
INFO 2013-08-16 13:46:48,660 Index=lmkfe insertTotal=11
INFO 2013-08-16 13:46:48,660 Index=lmkfe insertTotal=11

I would like to grep and extract the words that match my pattern which is abc:<some_number> and def:<some_number>.

$ cat "log.txt" | grep -w "abc" -w "def" >> "failed_values.txt";

So in this case, my failed_values.txt should only have

abc:12
def:134

The key to note is that my pattern ends with a : followed by a number and then a space e. g. abc:122.

like image 484
Macky Avatar asked Mar 23 '23 17:03

Macky


2 Answers

Try following:

$ grep  -Eio '[a-z]+:[0-9]+' log.txt 
abc:12
abcd:12
def:134
  • -i to ignore case.
  • -o to print only matched part.

UPDATE

To match only abc / def:

$ grep  -Eio '\b(abc|def):[0-9]+\b' log.txt 
abc:12
def:134
  • (abc|def):: match abc or(|) def followed by :.
  • [0-9]+: matched numbers.
  • \b: match word boundary
like image 130
falsetru Avatar answered Mar 25 '23 05:03

falsetru


$ grep -Eo "(abc|def):[0-9]*" log.txt
abc:12
def:134
like image 35
devnull Avatar answered Mar 25 '23 05:03

devnull