I've got a file that contains a list of key=value
pairs, each on its own line. What's the best way to fetch the value for a specified key using shell commands?
views:
223answers:
3@mouviciel, wrong comment location mate? (-:
Rob Wells
2010-02-25 15:54:52
A:
This is how I do it in ksh.
FOO=$(grep "^key=" $filename | awk -F"=" '{print $2}')
You can also use cut instead of awk. If you delimit the key pair with a space you can drop the -F"=".
Ethan Post
2010-02-25 15:28:37
grep can be omitted. awk can do it all. `awk -F"=" '/^key=/{print $2}'`
ghostdog74
2010-02-25 15:32:49
A:
read -r -p "Enter key to fetch: " key
awk -vk="$key" -F"=" '$1~k{ print "value for "k" is "$2} ' file
output
$ ./shell.sh
Enter key to fetch: key1
value for key1 is value1
or you can just use the shell(eg bash)
read -r -p "Enter key to fetch: " key
while IFS="=" read -r k v
do
case "$k" in
*"$key"* ) echo "value of key: $k is $v";;
esac
done <"file"
ghostdog74
2010-02-25 15:28:49
depends. if OP needs exact match. If not, regexp is appropriate. OP can implement a SQL "like" equivalent with regexp.
ghostdog74
2010-02-26 23:46:10