开发者

Use regex in awk command in bash script

开发者 https://www.devze.com 2022-12-23 23:23 出处:网络
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.

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 r开发者_如何学Goegex
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.


$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.


pass your shell variable to awk using -v option

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


I think you have a quoting problem

$ regex=asdf
$ echo '!/$regex/'
!/$regex/
$ echo "!/$regex/"
bash: !/$regex/: event not found
$ echo "\!/$regex/"
\!/asdf/
$ echo '!'"/$regex/"
!/asdf/
0

精彩评论

暂无评论...
验证码 换一张
取 消