简体   繁体   English

将带有单引号的awk程序嵌入到shell脚本中

[英]Embedding into a shell script an awk program with a single quote in it

I have a one line text file nik.txt and a simple awk script as follows: 我有一个单行文本文件nik.txt和一个简单的awk脚本,如下所示:

LagartijaNick>cat nik.txt
hey the're
LagartijaNick>cat tmp.awk
BEGIN {}
{
    searchName=tolower($0);
    if ( searchName ~ /'re/ ) {
       print $0
    }
}
LagartijaNick>awk -f tmp.awk nik.txt
hey the're

This above awk script prints the entire record as expected. 这个上面的awk脚本按预期打印了整个记录。 But now I have to embed the awk into a BASH script, like so: 但是现在我必须将awk嵌入到BASH脚本中,如下所示:

#!/bin/bash
infile=$1
function doThis () {
   awk 'BEGIN {}
   {
      searchName=tolower($0);
      if ( searchName ~ /'re/ ) {
         print $0
      }
   }' $infile
}
doThis
exit 0

This returns: 返回:

./tmp.sh: line 9: syntax error near unexpected token `)'
./tmp.sh: line 9: `   if ( searchName ~ /\'re/ ) {'

Simple, need to escape the single speech mark? 简单,是否需要转义单个语音标记? But I can't get it to work. 但是我无法正常工作。 I've tried: 我试过了:

if ( searchName ~ /\'re/ ) {
if ( searchName ~ /''re/ ) {

What am I doing wrong? 我究竟做错了什么? All I get are syntax error ... 我得到的只是语法错误...

I'm on the following version of bash: 我正在使用以下bash版本:

LagartijaNick>/bin/bash --version
GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)

Incorporating the suggestion of setting a variable with the single quote and removing the unnecessary BEGIN: 结合使用单引号设置变量并删除不必要的BEGIN的建议:

#!/bin/bash
infile=$1
function doThis () {
    read -d '' cmd <<EOA
    awk -vQ="'" '
    {
        searchName=tolower(\$0);
        if ( searchName ~ Q"re" ) {
            print \$0
        }
    }' $infile
EOA
    eval $cmd
}
doThis
exit 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM