2

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() {
    #pattern="$1"
    pacman -Sl | awk -v pattern="$1" '$2~ /^"pattern"/{print $2, $3, $4, "[" $1 "]"}' | sort
}
menteith
  • 270

1 Answers1

3

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.

Ex.

echo 'baz foobar' | awk -v pattern="foo" '$2 ~ "^"pattern {print $1}'
baz
steeldriver
  • 81,074