BASH: how to put a variable inside a regular expression?

I am trying to get the following code:

searchfile="availables.txt" read searchterm grep_params="-i ^.*${searchterm}.*;.*$' $searchfile" egrep $grep_params 

which should reflect all lines starting with $ searchterm followed by ";". But if the search engine contains spaces, it does not work (for example: "black eye pea"), it gives me the following result:

 egrep: eyed: No such file or directory egrep: peas.*;.*$": No such file or directory egrep: "availables.txt": No such file or directory 
+6
source share
6 answers

Just bash

 searchfile="file" read searchterm shopt -s nocasematch while read -r line do case "$line" in *"$searchterm"*";"* ) echo "$line";; esac done < "$searchfile" 
+2
source

You need to manage word splitting here. This 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, since the first is deprecated. But I would modify your code as follows:

 searchfile="availables.txt" read searchterm grep_params="^.*${searchterm}.*;.*$" grep -E -i "$grep_params" $searchfile 
+1
source

The code you are looking for looks something like this:

 searchfile="availables.txt" read searchterm regex="${searchterm}"'.*;' egrep "${grep_params}" "${searchfile}" 

Please note that I simplified your regex (hope everything is correct!).

However, as Ignacio Vazquez-Abrar noted, this will not work in difficult cases.

0
source

Since this is s regex, try replacing "<" with \s . This means a space character.

Black \ Seyed \ Speas

0
source

An alternative way is to pass parameters via xargs:

 searchfile="availables.txt" read searchterm grep_params="-i '^.*${searchterm}.*;.*$' $searchfile" echo "$grep_params" | xargs egrep 
0
source

I got here by searching for a bash variable in regex

I solved this by changing the regex separators from "/" to "+"

Even if this has nothing to do with egrep, I add my solution for other people who come from similar searches:

 SYBASELOG="/opt/sybase/ASE-12_5/install/SYBASE.log" MAILBODY="Some text and then the replacement placeholder: [MSGFILE] and some more text" # Some proecessing... MAILBODY=`echo "${MAILBODY}" | sed -e "s+\[MSGFILE\]+"${SYBASELOG}"+"` 

And yes, now I see that this has little to do with bash and everything related to the slash in the log file variable. D'o!

0
source

Source: https://habr.com/ru/post/886217/


All Articles