Reputation: 34026
I am trying to match a regular expression whose string part is contained in a variable as in :
matches=`grep "^"$*"[ ][0-9]\{1,\}" --count phonelist.txt`
where the regex would mean "any line in phonelist.txt which starts with the command line arguments followed by a space and a number with arbitrary many digits". Have tried many things but can't seem to get it. Help
Upvotes: 2
Views: 3412
Reputation: 360085
Give this a try:
matches=$(grep "^$* [0-9]\+" --count phonelist.txt)
Upvotes: 2
Reputation: 224691
If you want to treat each command line argument as a separate pattern (i.e. you want a “match” if a line starts with any of command line arguments), then you might construct your whole extended regular expression like this:
^(arg1|arg2|arg3|...) [0-9]+
You can use set IFS to |
and use $*
to automatically expand your positional parameters into that form like this:
(IFS=\|; echo "^($*) [0-9]+")
The parentheses form a subshell so that the changed IFS is limited to the commands in the parentheses (you may not want that setting to affect later parts of the script.
You will need to be careful when using command line arguments that contain extended regular expression metacharacters. For example, if you wanted to search for the literal string foo(bar)
, you would need to pass something like foo\(bar\)
as the argument (an ERE that matches the literal string), which you might write as 'foo\(bar\)'
on an actual command line.
Finally, put it back into your original command and tell grep
to expect an extended regular expression (-E
):
matches=$(IFS=\|; grep -E "^($*) [0-9]+" --count phonelist.txt)
The command substitution $()
is effectively its own subshell, so the modified IFS value will not “escape” into later parts of the script.
Upvotes: 2
Reputation: 14137
I think you should try:
IFS=" "
matches=$(grep "^$* [0-9]\+" --count phonelist.txt)
bash's man page says: $*
"expands to a single word with the value of each parameter separated by the first character of the IFS
special variable" whereas with $@
"each parameter expands to a separate word. That is, "$@
" is equivalent to "$1" "$2" ...".
In your regular expression you will need all the arguments joined into one single word.
Upvotes: 1