9

I found echo file|grep fil* fails, but echo abcd|grep abc* succeeds.

I don't understand it, can someone explain?

  • Can you add the system and the version of grep? This because with gnugrep 2.16 (under Ubuntu 14.04 LTS), it doesn't generate any error (exit code 0) and it matches the first three letters. For example, echo file|grep fil* answers with file. – Hastur Apr 28 '16 at 8:40
  • 3
    @Hastur The problem is caused by filename expansion before regular expression. My working directory contains a file prefixd by fil, but not a file prefixed by abc, so fil* is replaced by the filename, but abc* is unchanged. – tmpbin Apr 28 '16 at 9:20
  • Thanks I didn't think about it. When I do my attempts I try them in a new directory... – Hastur Apr 28 '16 at 9:34
31

There are two problems with your example.

The primary one is that you're assuming that regular expressions work the same as glob patterns in that * is a wildcard meaning "any sequence of characters." In regular expressions, * means "any number of the previous atom" instead, so fil* means f followed by i followed by zero or more l characters. You need to say grep fil.* to get the intended meaning: . means "any single character, so that .* means "any sequence of characters."

The lesser problem is that you're using unquoted special characters that mean something under glob rules, which means the shell could interpret them. If you had any files in the local directory matching the glob patterns fil* or abc*, the shell would expand them, so grep would get the expanded file names as a pattern, not the intended RE. Whenever you're using such characters on the command line, you should quote them: echo file | grep 'fil.*'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.