Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 657
pat Avatar asked Jun 11 '15 09:06

pat


2 Answers

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
like image 54
fedorqui 'SO stop harming' Avatar answered Oct 12 '22 11:10

fedorqui 'SO stop harming'


Simple way:

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-.

like image 39
Inanc Gumus Avatar answered Oct 12 '22 11:10

Inanc Gumus