shell – Pass Shell Variable as a Pattern to awk

awkquotingshellvariable

Having the following in one of my shell functions:

function _process () {
  awk -v l="$line" '
  BEGIN {p=0}
  /'"$1"'/ {p=1}
  END{ if(p) print l >> "outfile.txt" }
  '
}

, so when called as _process $arg, $arg gets passed as $1, and used as a search pattern. It works this way, because shell expands $1 in place of awk pattern! Also l can be used inside awk program, being declared with -v l="$line". All fine.

Is it possible in same manner give pattern to search as a variable?

Following will not work,

awk -v l="$line" -v search="$pattern" '
  BEGIN {p=0}
  /search/ {p=1}
  END{ if(p) print l >> "outfile.txt" }
  '

,as awk will not interpret /search/ as a variable, but instead literally.

Best Answer

Use awk's ~ operator, and you don't need to provide a literal regex on the right-hand side:

function _process () {
    awk -v l="$line" -v pattern="$1" '
        $0 ~ pattern {p=1} 
        END {if(p) print l >> "outfile.txt"}
    '  
}

Although this would be more efficient (don't have to read the whole file)

function _process () {
    grep -q "$1" && echo "$line"
}

Depending on the pattern, may want grep -Eq "$1"

Related Question