簡體   English   中英

在bash腳本中使用awk命令中的regex

[英]Use regex in awk command in bash script

我正在嘗試讀取正則表達式的文件,循環它們並將它們從另一個文件中過濾掉。 我很親密,但我相信我的$ regex var替換問題。

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

$ tempOne和$ tempTwo是臨時文件。 $ filterFile是包含正則表達式的文件。

$regex沒有擴展,因為它是單引號。 在bash中,擴展只能在雙引號字符串中完成:

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

所以,就像這樣分解你的字符串:

'!'"/$regex/"

它會表現得像你期望的那樣。 ! 不應該評估,因為這將執行歷史記錄中的最后一個命令。

使用-v選項將shell變量傳遞給awk

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

我認為你有一個引用問題

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM