How can I use a variable string in a regular expressions
while read line do if [[ line =~ *"$key"* ]]; then echo line fi done < "$filename"
$key is a string variable and I want to print all the lines that has the value of
You've made a few mistakes there. Here's your script corrected:
while read line do if [[ "$line" =~ "$key" ]]; then echo $line fi done < "$filename"
Though it seems it could be replaced with a simple
grep "$key" "$filename"
First, whenever you're using the value of a variable, you need to write
Also, note that
read line strips off leading and trailing whitespace, and allows the sequence backslash-newline as a line continuation. To retain whitespace, use
IFS= read. To avoid treating
\ specially, use
read -r. You can of course combine the two as
IFS= read -r.
What do you want to test exactly? If you want to test that the line is exactly
$key (except for whitespace unless you use
IFS= read), use the
== operator, and make sure to put
$key in double quotes.
if [[ $line == "$key" ]]; then …
If you want to test that the line contains
$key (so for example if the value of
fu*barqux match, but
gu*bar don't), then use the
== operator and again make sure to put
$key in double quotes. The right-hand side of the
== operator is a shell wildcard pattern; putting the variable in double quotes causes it to be treated literally.
if [[ $line == *"$key"* ]]; then …
If you want to treat
$key as a wildcard pattern, so that if
fu*bar then the line can be
fuqwebar but not
afubar, then leave off the double quotes:
if [[ $line == $key ]]; then …
If you only want part of the line to match, allowing things like
if [[ $line == *$key* ]]; then …
Use the regular expression match operator
=~ if you want to have an extended regular expression on the right-hand side. A regular expression can match part of the line; if you want to match the whole line, put
^ at the beginning of the regex and
$ at the end. For example,
[[ $line == *"$key"* ]] is equivalent to
[[ $line =~ "$key" ]] while
[[ $line == "$key" ]] is equivalent to
[[ $line =~ ^"$key"$ ]].