pat pat - 14 days ago 8
Linux Question

How to grep for value in a key-value store from plain text

Given a plain text file containing

FOO=foo
BAR=bar
BAZ=baz


How do we
grep
for the value using the key?

Answer

Use a look behind:

$ grep -Po '(?<=^FOO=)\w*$' file
foo

I also like awk for it:

$ awk -v FS="FOO=" 'NF>1{print $2}' file
foo

Or even better:

$ awk -F= -v key="FOO" '$1==key {print $2}' file
foo

With sed:

$ sed -n 's/^FOO=//p' file
foo

Or even with Bash -ONLY if you are confident about the file not containing any weird values-, you can source the file and echo the required value:

$ (source file; echo "$FOO")
foo