Search code examples
linuxshellgrepls

what is the difference between ls | grep *e* and ls | grep e


When used ls | grep *e* gives much lesser result than ls | grep e, why is it so. Are they not the same commands. Anybody knows the difference between these commands.


Solution

  • Are ls | grep *e* and ls | grep e not the same commands?

    No, they are different. With

    $ ls | grep *e*
    

    the command shell expands the pattern *e* to match all files which contain the letter e in the current directory. This expanded file list is then passed to the grep command:

    $ ls
    Hello.txt  Null.txt  Sample.txt
    

    When executing

    $ ls | grep *e*
    

    the actual command will be ls | grep Hello.txt Sample.txt

    With

    $ ls | grep e
    

    there is no file name expansion and the actual command will be ls | grep e.

    See also

    If you want to pass the parameter without being expanded, you need to quote it:

    $ ls | grep "*e*"
    

    Then, the command actually will be ls | grep *e* (with "*e*" being passed as argv[1] to the grep command).

    Note that the shell expansion is different from a regular expression - the shell matches any string for *, while in regular expressions * denotes that any number of the previous expression shall occur.