-1

I'm trying to read the entire config file "rest.conf" using the awk command. However I want the output to print the username.

rest.conf

username = test

function

function getProperty () {
echo $(awk '/^'$1'/{print $3}' "rest.conf")
}

getProperty "username"

Any idea's why I can't view username when I run the script?

Aaron
  • 65
  • 5

2 Answers2

0

Use awk's -v variable flag to pass shell variables into your awk script:

function getProperty () {
    awk -F' += +' -v property=$1  '$1 ~ property {print $2}' "rest.conf"
}

getProperty "username"

Also changes your Input Field Seperator to an equal sign with -F= and pulled the second field instead of the third. Also changed the Field Separator so whitespace doesn't pull through to the output.

Based on @123 input, removed the subshell since awk prints to stdout all by itself, and changed the regex to play friendly with awk variables.

JNevill
  • 46,980
  • 4
  • 38
  • 63
  • You've just solved a 4 hour problem of mine. Thanks a lot – Aaron Apr 27 '17 at 15:45
  • Why are you echoing the result of the subshell? – 123 Apr 27 '17 at 15:48
  • Also `/^property/` matches the literal string property not your variable. – 123 Apr 27 '17 at 15:50
  • You may also want to change the field separator to `-F'+= +'` or you will have a space before the output. The `echo $()` will have previously masked this issue. You could also change `-vproperty="^$1$"` to get an exact match. – 123 Apr 27 '17 at 16:00
  • Thanks @123 That `-F` is perfect. – JNevill Apr 27 '17 at 16:02
  • ITYM `-F' += +'` or more robustly `-F'[[:space:]]*=[[:space:]]*'`. Also wrt @123's comment using `-vproperty=` would make the script unnecessarily gawk-specific. Always put a space between `-v` and the variable name (i.e. `-v property=`) as shown in the answer and to get an exact match you'd use `-v property="$1" ... $1 == property` rather than a regexp. Right now username `John` would match `Johnson`, etc. Finally - bash functions are defined by the syntax `function foo` or `foo()`, not `function foo ()`. Use `foo()` for portability. – Ed Morton Apr 27 '17 at 16:17
  • 1
    @EdMorton Didn't know `-vVar` was gawk specific, and yes i did mean `-F' += +'`. Regarding the match, it is unclear whether OP may require regex or not which is why I didn't suggest `==`. – 123 Apr 27 '17 at 16:26
0

This is how to write your code portably, robustly, and efficiently:

getProperty() {
    awk -F'[[:space:]]*=[[:space:]]*' -v property="$1" '$1 == property{print $2; exit}' "rest.conf"
}

getProperty "username"
Ed Morton
  • 188,023
  • 17
  • 78
  • 185