Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH: how to put variable inside regex?

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
like image 552
Alessio Avatar asked Apr 19 '11 07:04

Alessio


People also ask

How do you write a variable inside a regular expression?

Solution 1. let year = 'II'; let sem = 'I'; let regex = new RegExp(`${year} B. Tech ${sem} Sem`, "g"); You need to pass the options to the RegExp constructor, and remove the regex literal delimiters from your string.

Can you have variables in regex?

Note: Regex can be created in two ways first one is regex literal and the second one is regex constructor method ( new RegExp() ). If we try to pass a variable to the regex literal pattern it won't work. The right way of doing it is by using a regular expression constructor new RegExp() .

What does %% mean in bash?

So as far as I can tell, %% doesn't have any special meaning in a bash function name. It would be just like using XX instead. This is despite the definition of a name in the manpage: name A word consisting only of alphanumeric characters and under- scores, and beginning with an alphabetic character or an under- score.

Can you grep a variable?

But, what if you want to grep a string in a variable? If you pass a variable as an argument to grep, you will get an error (or several if your variable contains spaces). This happens because the variable is expanded by the shell. When expanded, grep recognizes it as multiple arguments where a filename should be.


1 Answers

Just Bash

searchfile="file"
read searchterm
shopt -s nocasematch
while read -r line
do
    case "$line" in
        *"$searchterm"*";"* ) echo "$line";;
    esac
done < "$searchfile"
like image 196
bash-o-logist Avatar answered Sep 22 '22 10:09

bash-o-logist