[英]Use regex in awk command in bash script
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. 我很亲密,但我相信我的$ regex var替换问题。
while read regex
do
awk -vRS= '!/$regex/' ORS="\n\n" $tempOne > $tempTwo
mv $tempTwo $tempOne
done < $filterFile
$tempOne and $tempTwo are temporary files. $ tempOne和$ tempTwo是临时文件。 $filterFile is the file containing the regexes. $ filterFile是包含正则表达式的文件。
$regex
is not getting expanded because it is single quoted. $regex
没有扩展,因为它是单引号。 In bash, expansions are only done in doublequoted strings: 在bash中,扩展只能在双引号字符串中完成:
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 使用-v
选项将shell变量传递给awk
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/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.