LagartijaNick
LagartijaNick

Reputation: 18

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:

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. But now I have to embed the awk into a BASH script, like so:

#!/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:

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

Upvotes: 0

Views: 350

Answers (1)

rocky
rocky

Reputation: 7098

Incorporating the suggestion of setting a variable with the single quote and removing the unnecessary 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

Upvotes: 1

Related Questions