Select a block starting with "189 common" ending in "48"
Sample file:

2992 common TG:XGE0/0/31(U) XGE0/0/32(U) XGE0/0/33(U) XGE0/0/34(U) XGE0/0/35(U) XGE0/0/36(U) XGE0/0/37(U) XGE0/0/38(U) XGE0/0/39(U) XGE0/0/47(U) XGE0/0/48(D) 2993 common TG:XGE0/0/31(U) XGE0/0/32(U) XGE0/0/33(U) XGE0/0/34(U) XGE0/0/35(U) XGE0/0/36(U) XGE0/0/37(U) XGE0/0/38(U) XGE0/0/39(U) XGE0/0/47(U) XGE0/0/48(D) 2994 common TG:XGE0/0/31(U) XGE0/0/32(U) XGE0/0/33(U) XGE0/0/34(U) XGE0/0/35(U) XGE0/0/36(U) XGE0/0/37(U) XGE0/0/38(U) XGE0/0/39(U) XGE0/0/47(U) XGE0/0/48(D) 2995 common TG:XGE0/0/31(U) XGE0/0/32(U) XGE0/0/33(U) XGE0/0/34(U) XGE0/0/35(U) XGE0/0/36(U) XGE0/0/37(U) XGE0/0/38(U) XGE0/0/39(U) XGE0/0/47(U) XGE0/0/48(D) 2996 common TG:XGE0/0/31(U) XGE0/0/32(U) XGE0/0/33(U) XGE0/0/34(U) XGE0/0/35(U) XGE0/0/36(U) XGE0/0/37(U) XGE0/0/38(U) XGE0/0/39(U) XGE0/0/47(U) XGE0/0/48(D) 

This is how it works:

 cat vlan_port_hu.db | awk ' /^189 common/,/48/ {print} ' 

but I need to substitute the value from the variable in the place "189":
I try this:

 #/bin/bash while read vlanid vlanname do cat vlan_port_hu.db | awk ' /^$vlanid common/,/48/ {print} ' done < ~/vlan_hu.db 

Does not work.
How to do? It is very desirable in bash, but it is possible in other languages.

    2 answers 2

    To use environment variables as placeholders in strings , it is necessary to frame the string with double quotes " , i.e.

     VAL=2993; cat vlan_port_hu.db | awk " /^${VAL} common/,/2995/ {print} " 

    A similar convention is used in some programming languages.

      You can pass a variable like this:

       awk -v myvar="$bash_var" '{ myvar ... }' file 

      In your case:

       #!/bin/bash while IFS= read -r vlanid vlanname do awk -v var=$vlanid '$0 ~ "^" var " common", /48/' vlan_port_hu.db done < ~/vlan_hu.db 

      Test

       $ seq 20 > a $ awk -v var=5 '$0 ~ "^" var,/12/' a 5 6 7 8 9 10 11 12 $ awk -v var=7 '$0 ~ "^" var,/12/' a 7 8 9 10 11 12 
      • awk: fatal: cannot open file `$ 0 ~" ^ "var" common ", / 48 / 'for reading (No such file or directory) - Izya12
      • @ Izya12 which team do you work exactly? - fedorqui