Reputation: 509
I'm trying to grep over files which have names matching regexp. But following:
#!/bin/bash
grep -o -e "[a-zA-Z]\{1,\}" $1 -h --include=$2 -R
is working only in some cases. When I call this script like that:
./script.sh dir1/ [A-La-l]+
it doesn't work. But following:
./script.sh dir1/ \*.txt
works fine. I have also tried passing arguments within double-quotes and quotes but neither worked for me. Do you have any ideas how to solve this problem?
Upvotes: 0
Views: 73
Reputation: 44023
grep
's --include
option does not accept a regex but a glob (such as *.txt
), which is considerably less powerful. You will have to decide whether you want to match regexes or globs -- *.txt
is not a valid regex (the equivalent regex is .*\.txt
) while [A-La-l]+
is not a valid glob.
If you want to do it with regexes, you will not be able to do it with grep
alone. One thing you could do is to leave the file selection to a different tool such as find
:
find "$1" -type f -regex "$2" -exec grep -o -e '[a-zA-Z]\{1,\}' -h '{}' +
This will construct and run a command grep -o -e '[a-zA-Z]\{1,\}' -h list of files in $1 matching the regex $2
. If you replace the +
with \;
, it will run the command for each file individually, which should yield the same results (very) slightly more slowly.
If you want to do it with globs, you can carry on as before; your code already does that. You should put double quotes around $1
and $2
, though.
Upvotes: 2