Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extracting a variable's value from text file using bash

Tags:

bash

I am using Linux and bash. I have a simple text file like below:

VAR1=100
VAR2=5
VAR3=0
VAR4=99

I want to extract by means of bash the value of VAR2, that is 5.

How could I do that?

like image 573
Saverio Avatar asked Jul 13 '26 08:07

Saverio


2 Answers

Assuming the file is called vars.txt

sed -n 's/^VAR2=\(.*\)/\1/p' < vars.txt

You can use the value elsewhere like this using single back quotes

echo VAR2=`sed -n 's/^VAR2=\(.*\)/\1/p' < txt`
like image 174
noahcoad Avatar answered Jul 19 '26 00:07

noahcoad


The simplest way might be to use source or simply . to read and execute the file. This would work with your example, because there are no spaces in the variable values. Otherwise you need to use grep + cut or awk, as stated in other answers.

. /path/to/your/file
echo $VAR2

[edit] As stated by dawg, this would make the other variables available in your script too, and possibly overwrite existing variables.

like image 37
visit1985 Avatar answered Jul 19 '26 00:07

visit1985



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!