Shell UNIX : grep wild card

bash, grep, shell, unix, wildcard

Solution

The first argument to `grep` is not a wildcard, it's a regular expression. In a regular expression, `*` means to match any number of the character or expression that precedes it. So

grep "tgt/etc/*"

means to match `tgt/etc` followed by zero or more `/` characters. In a wildcard, `*` means to match any number of any characters, the equivalent regular expression is `.*`. For your purposes, the commands you want are:

find . -type f -name \* | grep "tgt/etc/"
find . -type f -name \* | grep "tgt/et.*/s"

Also, if you don't quote the argument, and it contains any `*` characters, the shell will expand the argument as a filename wildcard before passing them as arguments to `grep`. So when you write:

find . -type f -name \* | grep tgt/etc/*

the shell will expand this to

find . -type f -name \* | grep tgt/etc/file1 tgt/etc/file2 tgt/etc/file3

This will treat the `tgt/etc/file1` as the regular expression to search for, and look for it inside the remaining files -- it will not process the input from the pipeline because it was given filename arguments.

Problem

I can't figure out why the wild character * is interpreted differently in the following examples with grep : ``` find . -type f -name \* ``` Results : ``` ./tgt/etc/test_file.c ./tgt/etc/speleo/test_file.c ./tgt/etc/other_file.c ./src/file.c ``` I want to return from this command the files that match a pattern with eventually a wildcard *. But : ``` find . -type f -name \* | grep "tgt/etc/*" # this one works find . -type f -name \* | grep tgt/etc/* # not this one find . -type f -name \* | grep tgt/et*/s* # this one works find . -type f -name \* | grep "tgt/et*/s*" # not this one ``` I'd like to have an implementation which works fine with both cases. What should I use ?

Original source