Grep to extract the word matching the given patter

2019-06-24 04:27发布

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.

标签: shell unix
3条回答
We Are One
2楼-- · 2019-06-24 04:54

This should do it:

grep "[ad][be][cf]:[0-9]*" [your file]

查看更多
ら.Afraid
3楼-- · 2019-06-24 05:07
$ grep -Eo "(abc|def):[0-9]*" log.txt
abc:12
def:134
查看更多
Fickle 薄情
4楼-- · 2019-06-24 05:15

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
查看更多
登录 后发表回答