3
  1. How to insert bash variables in awk (for example i need to do in in some for loop - like this: in first iteration use awk to search string by first column, next by second column and so on with using diffent pattern from bash variables in awk)

or

  1. find the simple way to make pattern at all (as string) and recieve it to awk as argument.

Trying to insert bash variables in awk -

I have some log -

$ cat > log
test1
test2
ahaha
hahah

i do

$ cat log | awk '$1~/test1|test2/ {print }'
test1
test2

all ok

i need to paste bash variables in awk

$ a=test1
$ b=test2

then i try to insert

$ cat log | awk 'BEGIN{a;b} $1~/a|b/ {print }'
ahaha
hahah

$ cat log |  awk -v a=test1 -v b=test2 '$1~/a|b/ {print }'
ahaha
hahah

How to make all patern as string and recieve it to awk as argument -

$ p='$1~/test1|test2/ {print }'

$ cat log | awk p
# get test1
# get test2
0
4

Awk does not expand variables inside /.../.

But

$ cat log |  awk -v a=test1 -v b=test2 '$1 ~ a || $1 ~ b {print }'

and

$ p='$1~/test1|test2/ {print }'
$ cat log |  awk "$p"

should work (untested)

3

Pass the patterns as variables to awk and compare explicitly using dynamic patterns (i.e. match against patterns in strings)...

awk -v pat="$a|$b" '$1 ~ pat' log

or

awk -v a="$a" -v b="$b" '$1 ~ a "|" b ' log

Note: You can't use static patterns /.../ (or only by using dirty quoting/escaping).

2
  • it doesn't work as i want. no search availiable in this example. $ awk -v pat="$a|$b" '$1 ~ pat' log - show all strings and $ awk -v a="$a" -v b="$b" '$1 ~ a "|" b ' log too.
    – dmgl
    Feb 11 '15 at 18:02
  • blackbird, you must have done something wrong. I just confirmed my two proposals with bash and ksh.
    – Janis
    Feb 27 '15 at 21:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.