skip to Main Content

On CentOS 8, this grep expresssion does not return matched strings:

% dmidecode -t memory | grep -E '^[ t]+Size: [0-9]+'

However this one does return matched lines correctly (on the same distro):

% dmidecode -t memory | grep -E '^[[:space:]]+Size: [0-9]+'

What is the reason of such behaviour? As you can see both times grep is invoked in extended regexp mode.

2

Answers


  1. Use [[:blank:]] which matches space char and tab char. You can omit -E too:

    grep '^[[:blank:]]+ Size: [0-9]+'
    
    Login or Signup to reply.
  2. The issue here is the t character sequence. This does not match a tab character in a grep regular expression, it matches the character t (Doesn’t matter if it’s basic or extended dialect RE). It’s not treated as a special escape sequence the way it is by some other tools (Including GNU grep using the PCRE dialect).

    Witness:

    # printf /does/ treat t and n special in a format
    $ printf "atbn" | grep "a[ t]b" # No match
    $ printf  "atbn" | grep "a[ t]b" # Match
    atb
    $ printf "atbn" | grep "a[[:space:]]b" # Match
    a     b
    $ printf "atbn" | grep "a[[:blank:]]b" # Match
    a     b
    $ printf "atbn" | grep "asb" # Match, s is a GNU grep extension
    a     b
    $ printf "atbn" | grep -P "asb" # Match, GNU grep using PCRE
    a     b
    $ printf "atbn" | grep -P "a[ t]b" # Match, GNU grep using PCRE.
    a     b
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search