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
Share:
13,685
Alessio
Author by

Alessio

Updated on June 14, 2022

Comments

  • Alessio
    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
    Ignacio Vazquez-Abrams about 13 years
    This will also match other whitespace characters, which may not be what is intended.
  • Alessio
    Alessio about 13 years
    thanks, also: Is there any way to escape all spaces, brackets, etc.? So i can put in searchterm the string ".*"
  • Draco Ater
    Draco Ater about 13 years
    Didn't get you. What forbids you to enter .* when being asked for searchterm?
  • Alessio
    Alessio about 13 years
    if i enter ".*", it matches all the line
  • Draco Ater
    Draco Ater about 13 years
    Remove .*$ in the grep_params, then it will match up to the ";"
  • Alessio
    Alessio about 13 years
    well, 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
    Draco Ater about 13 years