Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code for parsing a key/value in in file from shell script

Tags:

linux

bash

I have a file that I need to look up a value by key using a shell script. The file looks like:

HereIsAKey This is the value

How can I do something like:

MyVar=Get HereIsAKey

and then MyVar should equal "This is the value". The key has no whitespace and the value should be everything following whitespace after the key.

like image 256
Edwin Evans Avatar asked Mar 12 '13 15:03

Edwin Evans


2 Answers

if HereIsAKey is unique in your file, try this with grep:

myVar=$(grep -Po "(?<=^HereIsAKey ).*" file)
like image 87
Kent Avatar answered Sep 28 '22 19:09

Kent


If you don't have a grep that supports Perl-compatible regular expressions, the following seems to work:

VAR=$(grep "^$KEY " file | cut -d' ' -f2-)
like image 23
Roger Lipscombe Avatar answered Sep 28 '22 18:09

Roger Lipscombe