I would like to know how to pass a argument to a Bash function which would consequently serve as a pattern to awk. I have read several Q/As which tend to answer the same question, however, I am missing something.

I use the following one-liner to find a package, which in this example is vivaldi, using Arch Linux packman:

 pacman -Sl | awk '$2~ /^vivaldi/{print $2, $3, $4, "[" $1 "]"}' | sort

I've written the following function but executing it outputs no result:

function pacname() {
    pacman -Sl | awk -v pattern="$1" '$2~ /^"pattern"/{print $2, $3, $4, "[" $1 "]"}' | sort

Variables are not expanded inside Awk's /.../ regex. Instead you can use the string form "^"pattern to concatenate the anchor operator with a variable pattern value.


echo 'baz foobar' | awk -v pattern="foo" '$2 ~ "^"pattern {print $1}'
  • 3
    Or even construct the regex in the -v text: awk -v pattern="^$1" '$2 ~ pattern {... Mar 6 '19 at 18:28

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