caret character unexpected behaviour in regular expressions with grep

i was running grep commands from "William Shotts" regular expressions example.It seems,the caret character is not doing what it is supposed to do.
I have four test files with all the bin entries in text form.My intention is to find the keywords starting with "zip" from my 4 files(all file names starting with "dirlist"),So ran the command like below:

grep '^zip' dirlist*.txt

It should return keywords like zip,zipgrep etc but it is not functioning at all.Please help!
What i am doing wrong?

Asked By: S.Das

||

My intention is to find the keywords starting with "zip"

The caret ^ matches the beginning of a line and not the beginning of a word … Therefore, grep '^zip' dirlist*.txt will only match zip if it’s in the beginning of a line.

To match whole words beginning with zip anywhere in the line instead, you can use the -w option … from man grep:

   -w, --word-regexp
          Select only those lines containing matches that form whole words.  The test is that
          the  matching substring must either be at the beginning of the line, or preceded by
          a non-word constituent character.  Similarly, it must be either at the end  of  the
          line  or followed by a non-word constituent character.  Word-constituent characters
          are letters, digits, and the underscore.

… and form your RegEx with zip followed by zero or more word characters w* like so:

grep -w 'zipw*' dirlist*.txt

… or, similarly, use word boundary b instead of -w like so:

grep 'bzipw*b' dirlist*.txt

It should return keywords like zip,zipgrep etc

To return only the matched part by the RegEx and not the whole line containing the match, you can use grep‘s option -o:

   -o, --only-matching
          Print only the matched (non-empty) parts of a matching line, with each such part on
          a separate output line.

… like so:

grep -ow 'zipw*' dirlist*.txt

… or so:

grep -o 'bzipw*b' dirlist*.txt
Answered By: Raffa
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.