Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this regex work for grep?

Tags:

regex

linux

grep

I'm trying to remove "Packet number 624 doesn't match" from a response so the obvious thing to try is

cat somefile.txt | grep -v "Packet number \d+ doesn't match"

If I remove the -v, just for testing, then it returns nothing. So maybe the command line is doing something with the \d or + first. So I have tried various combinations such as \\d+ \\d\+ \\\\d+ \\\\d\+ [0-9]+ [0-9]\+. Bingo!! That last one worked. Can someone explain what is going on here? If this is getting modified by the command line why does echo "\d+" still return \d+?

like image 870
MikeKulls Avatar asked Sep 18 '25 01:09

MikeKulls


1 Answers

By default, grep uses basic regular expression and \d is (PCRE) syntax. It is not supported so you'll need to use ( [0-9] ) or ( [[:digit:]] ) instead, or use grep with option -P

Why doesn't [0-9]+ work?

  • In BRE, meta-characters like + lose their meaning and need to be escaped.

You can fix this by using one of the following:

grep -v "Packet number [0-9]\+ doesn't match"

OR

grep -v "Packet number [[:digit:]]\+ doesn't match"
like image 111
hwnd Avatar answered Sep 20 '25 23:09

hwnd