Search code examples
regexshellgrepglob

grep filename[asterisk] returns unexpected result


I have a basic question about ls command. Suppose in a directory I have 4 files named

run
run1
running
run.sh

So, if i do: ls -l|grep run* then I get no result.

But if i do ls -l|grep run.* then I get run.sh as a result.

However I expected grep to list all of the files in both the cases. Could you make me understand what is going on behind scenes?


Solution

  • As long as I understand, the "*" is expanded by the shell before executing the command itself, so your grep will try to catch a string with all the file names! On the other hand, grep expects a regular expression, so the "*" is not interpreted as you expect.

    The direct solution would be:

    $ ls -l run*
    

    Or, if you want to use grep, then scape the "*" and provide a regular expression:

    $ ls -l|grep run.\*
    $ ls -l|grep 'run.*'