Search code examples
bashshellvariablesawkquoting

Pass shell variable to the beginning of awk search pattern


I could pass a variable into the pattern of awk but I'm not sure what I should do if this variable is at the beginning of the pattern so here is an expample code

    awk -v pattern="$i" '
       $0 ~ /^$pattern/{print}
    ' input.txt

The code below works for searching the pattern only,

    awk -v pattern="$i" '
       $0 ~ pattern{print}
    ' input.txt

What should I do to combine variables and regular expressions?


Solution

  • 1st solution: Could you please try following.

    awk -v pattern="$i" 'match($0,"^" pattern)' Input_file
    


    2nd solution with index:

    awk -v pattern="$i" 'index($0,pattern)==1'  Input_file
    


    3rd solution using substr:

    i- To get a match.

    awk -v pattern="$i" 'BEGIN{var_len=length(pattern)} substr($0,1,var_len)~pattern  Input_file
    

    ii- To get EXACT match:

    awk -v pattern="$i" 'BEGIN{var_len=length(pattern)} substr($0,1,var_len)==pattern'  Input_file