2

This question already has an answer here:

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
}

marked as duplicate by Kusalananda awk Mar 6 at 18:42

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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
  • 3
    Or even construct the regex in the -v text: awk -v pattern="^$1" '$2 ~ pattern {... – glenn jackman Mar 6 at 18:28

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