Given a plain text file containing
FOO=foo
BAR=bar
BAZ=baz
How do we grep for the value using the key?
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
grep "^FOO=" | cut -d"=" -f2-
I prefer this because it's very easy to remember for me.
Explanation: It simply greps the line starting with FOO (hence the ^) and cutting it with = to pieces and then getting the second piece with -f2-.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With