0

I'm trying to parse key=value pair using awk in a bash script

A sample key/value is like:

time=2

where I can retrieve the value using something like this:

echo time="2" | awk -F= '$1=="time"{print $2}'

Now I want to put this in a bash script, and use a function to specify the key to retrieve the value, basically have an argument, something like this (which does not work) :

get_value() {
    variable=$1
    echo time="2" | awk -F= '$1=="${variable}"{print $2}'
}

get_value "time"

How should I handle this case?

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Mahyar
  • 1,011
  • 2
  • 17
  • 37
  • you are trying to use shell variable inside awk. See [this](https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script) – downtheroad Mar 14 '19 at 18:34
  • change `awk -F= '$1=="${variable}"{print $2}'` to `awk -F= -v variable="${variable}" '$1==variable{print $2}'` note that , you were trying to use bash variable `${variable}` inside `awk`'s scope. you need to make `awk` aware of it by doing `-v ....` – P.... Mar 14 '19 at 18:35

0 Answers0