Standard grep
does not by default understand Perl-like regular expressions (PCRE) such as \w
. GNU grep
does handle \w
(and \W
) even in basic and extended regular expressions, which is an extension to the standard behaviour. Other PCRE is enabled in GNU grep
using its -P
option.
The reason your command returns nothing is that +
is an extended regular expression operator, which needs -E
to work in GNU grep
:
grep -E '^--\w+' file
Without -E
, your expression tries to match --W+
literally (where W
is some single character matched by \w
).
Also note that you may want to anchor the expression at the end as well, as in
grep -E '^--\w+$' file
or else you'll match lines containing non-\w
characters later, like
--00000000=
Alternatively, you may use
grep -xE -e '--\w+' file
which does the same thing. The -x
option forces a full line match. The -e
is needed to delimit the expression from the command line options as the pattern starts with a dash.
GNU grep
also understands \+
in basic regular expressions (i.e. when using grep
without -E
or -P
):
grep -x -e '--\w\+' file
Or you could use \{1,\}
in place of the \+
.
With a non-GNU grep
(and GNU grep
), you may use [[:alnum:]_]
(which matches a letter or a digit, or an underscore which is included separately here) in place of \w
:
grep -xE -e '--[[:alnum:]_]+' file
To match hexadecimal numbers and underscores, use [[:xdigit:]_]
:
grep -xE -e '--[[:xdigit:]_]+' file
or,
LC_ALL=C grep -xE -e '--[0-9a-fA-F_]+' file
The setting of LC_ALL
to C
(or to POSIX
) for the grep
command is necessary since character ranges are locale dependent.