views:

223

answers:

3

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?

+1  A: 

what about

grep "key" my_file | cut -d'=' -f2
Rob Wells
@mouviciel, wrong comment location mate? (-:
Rob Wells
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
grep can be omitted. awk can do it all. `awk -F"=" '/^key=/{print $2}'`
ghostdog74
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
may not even need a regexp: `awk ... '$1 == k {print $2}' file`
glenn jackman
depends. if OP needs exact match. If not, regexp is appropriate. OP can implement a SQL "like" equivalent with regexp.
ghostdog74