Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use regex in awk command in bash script

Tags:

regex

bash

awk

I'm trying to read a file of regexes, looping over them and filtering them out of another file. I'm so close, but I'm having issues with my $regex var substitution I believe.

while read regex
do
  awk -vRS= '!/$regex/' ORS="\n\n" $tempOne > $tempTwo
  mv $tempTwo $tempOne
done < $filterFile

$tempOne and $tempTwo are temporary files. $filterFile is the file containing the regexes.

like image 230
fmpdmb Avatar asked Feb 26 '26 16:02

fmpdmb


1 Answers

$regex is not getting expanded because it is single quoted. In bash, expansions are only done in doublequoted strings:

foo="bar"
echo '$foo'  # --> $foo
echo "$foo"  # --> bar

So, just break up your string like so:

'!'"/$regex/"

and it will behave as you expect. The ! should not be evaluated, since that will execute the last command in your history.

like image 135
vezult Avatar answered Mar 01 '26 10:03

vezult