1. Use either named classes or PCRE
GNU grep
uses by default Basic Regular Expressions (BRE), but it also let you use Extended Regular Expressions (ERE) and Perl-compatible Regular Expressions (PCRE).
Please note that neither BRE nor ERE support \s
nor \d
, but they have similar features. From man grep
:
Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:]
, [:alpha:]
, [:cntrl:]
, [:digit:]
, [:graph:]
, [:lower:]
, [:print:]
, [:punct:]
, [:space:]
, [:upper:]
, and [:xdigit:]
. For example, [[:alnum:]]
means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]
. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ]
place it first in the list. Similarly, to include a literal ^
place it anywhere but first. Finally, to include a literal -
place it last.
Example:
$ grep -E '^[[:digit:]]+$' << 'EOF'
> foo
> 123
> bar
> EOF
123
You may also use PCRE, as it supports \s
and \d
:
$ grep -P '^\d+$' << 'EOF'
> foo
> 123
> bar
> EOF
123
2. \n
doesn't work
In Unix every \n
delimits a line. grep
prints lines that match a given pattern. Matching \n
itself wouldn't make sense in this context.
You could either use $
to match the end of the line:
$ grep -E 'foo bar$' << 'EOF'
> foo
> foo bar
> foo bar baz
> EOF
foo bar
or pass the -z
/--null-data
option to activate the "multiline" mode (you'll need some extra workarounds to exactly match what you want):
$ grep -Poz '(?<=\n)?foo bar\n' << 'EOF'
> foo
> foo bar
> foo bar baz
> EOF
foo bar
3. Your first example doesn't do what you think
That last \s
will match line 1
and line 3
instead of line 2
and line 4
:
$ grep -P 'Patient\s\d+\s' << 'EOF'
> line1 Patient 123 45566
> line2 Patient 432
> line3 Patient 234 456
> line4 Patient 321
> line5
> EOF
line1 Patient 123 45566
line3 Patient 234 456
grep
does POSIX basic or extended regular expressions, or PCRE if you're using GNUgrep
and the-P
option. Whatgrep
are you using (are you on Linux)? – Kusalananda Feb 05 '19 at 23:40grep -V; grep (BSD grep) 2.5.1-FreeBSD
also tried withgrep (GNU grep) 2.27
– lacostenycoder Feb 05 '19 at 23:49Patient\s\d+[^\s]$
– jsotola Feb 06 '19 at 04:31