4

I have a linux config file with with format like this:

VARIABLE=5753
VARIABLE2=""
....

How would I get f.e. value of VARIABLE2 using standard linux tools or regular expressions? (I need to parse directory path from file). Thanks in advance.

Tomas Pruzina
  • 8,397
  • 6
  • 26
  • 39
  • maybe I am not getting this, but why don't you write `echo $VARIABLE2`? – Ivaylo Strandjev Mar 04 '12 at 09:23
  • 2
    you don't want to source that whole file? – Mat Mar 04 '12 at 09:24
  • It's been nearly 3 years so I don't even remember, but I think I went for right answer. Sourcing whole config wasn't an option, I wasn't about to execute "." on potentially untrusted / corrupted config, so I went for perl regex matching thing and then filtered results by extra regulars (there was a optional name for tmpdir in variable in my script and I didnt wanted it to be "~" or "/" which would result in "rm -r ~" afterwards. – Tomas Pruzina Jan 25 '15 at 00:05

3 Answers3

7

You could use the source (a.k.a. .) command to load all of the variables in the file into the current shell:

$ source myfile.config

Now you have access to the values of the variables defined inside the file:

$ echo $VARIABLE
5753
Dawngerpony
  • 3,288
  • 2
  • 34
  • 32
5
eval $(grep "^VARIABLE=" configfile)

will select the line and evaluate it in the current bash context, setting the variable value. After doing this, you will have a variable named VARIABLE with value 5753. If no such line exists in the configfile, nothing happens.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
5
$> cat ./text 
VARIABLE=5753
VARIABLE2=""

With perl regular expression grep could match these value using lookbehind operator.

$> grep --only-matching --perl-regex "(?<=VARIABLE2\=).*" ./text
""

And for VARIABLE:

$> grep --only-matching --perl-regex "(?<=VARIABLE\=).*" ./text
5753