BASH: how to put variable inside regex?
13,685
Solution 1
Just Bash
searchfile="file"
read searchterm
shopt -s nocasematch
while read -r line
do
case "$line" in
*"$searchterm"*";"* ) echo "$line";;
esac
done < "$searchfile"
Solution 2
You need to control word splitting here. That is done through arrays. See http://mywiki.wooledge.org/WordSplitting
searchfile="availables.txt"
read searchterm
grep_params=(-i "^.*${searchterm}.*;.*$" $searchfile)
egrep "${grep_params[@]}"
But don't use egrep
- use grep -E
instead, as the first is deprecated.
But I would have changed your code like that:
searchfile="availables.txt"
read searchterm
grep_params="^.*${searchterm}.*;.*$"
grep -E -i "$grep_params" $searchfile
Author by
Alessio
Updated on June 14, 2022Comments
-
Alessio almost 2 years
i'm trying to get working the following code:
searchfile="availables.txt" read searchterm grep_params="-i ^.*${searchterm}.*;.*$' $searchfile" egrep $grep_params
which should echo all lines beginning with the $searchterm and followed by ";". But if the searchterm contains spaces it doesn't work (eg: "black eyed peas"), it gives me the following output:
egrep: eyed: No such file or directory egrep: peas.*;.*$": No such file or directory egrep: "availables.txt": No such file or directory
-
Ignacio Vazquez-Abrams about 13 yearsThis will also match other whitespace characters, which may not be what is intended.
-
Alessio about 13 yearsthanks, also: Is there any way to escape all spaces, brackets, etc.? So i can put in searchterm the string ".*"
-
Draco Ater about 13 yearsDidn't get you. What forbids you to enter
.*
when being asked forsearchterm
? -
Alessio about 13 yearsif i enter ".*", it matches all the line
-
Draco Ater about 13 yearsRemove
.*$
in the grep_params, then it will match up to the ";" -
Alessio about 13 yearswell, if i enter ".*", it should matches only lines that have "something.*something;something". Instead it matches all lines. I would have something that converts the string ".*" into "\.*", in other words something that escape all the special character like .,\,/,*,$, etc
-
Draco Ater about 13 years