How to insert bash variables in awk?
11,177
Solution 1
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)
Solution 2
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).
Related videos on Youtube
Author by
dmgl
Updated on September 18, 2022Comments
-
dmgl over 1 year
- 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
- 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
-
dmgl over 9 yearsit 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.