AishwaryaK
AishwaryaK

Reputation: 71

Fetching the value of variable stored in a file

I am trying to fetch the output of a variable stored in a file in another shell script. Example:

cat abc.log
  var1=2
  var2=2
  var3=25

I am writing a script to fetch the value of var3.

Thank you in advance.

Upvotes: 0

Views: 191

Answers (3)

M. Nejat Aydin
M. Nejat Aydin

Reputation: 10113

A grep one-liner, if your grep has support for Perl-compatible regular expressions (the -P option; not all greps support that)

grep -Po '^\s*var3=\K.*' abc.log

or,

grep -Po '^\s*var3=\K.*' abc.log | tail -n1

in order to get the last value of the var3, if multiple var3s is a possibility.

Upvotes: 1

Raman Sailopal
Raman Sailopal

Reputation: 12867

awk -F= '$1 ~ /^[[:space:]]*var3/  { print $2 }' abc.log

Set the field delimiter to = and then where the line contains "var3", print the second field.

Alternatively, you could:

source abc.log

and then:

echo $var3

Upvotes: 3

David C. Rankin
David C. Rankin

Reputation: 84521

Using sed you can isolate 25 with particularity with:

sed -n '/^[[:space:]]*var3=/s/^[^=]*=//p' file

Explanation

This is the general substitution form s/find/replace/ with a matching expression preceding it. The total form is /match/s/find/replace/. The option -n suppresses the normal printing of pattern-space and the p at the end tells sed to print the line where the match and substitution took place. Specifically,

  • /match/ locates a line with any number of preceding whitespace characters followed by var3=. The POSIX [:space:] character class matches any whitespace,
  • the /find/ is all characters anchored from the '^' beginning that are not the [^=] character and then match the literal '=' character, and finally
  • the /replace/ is the empty-string leaving the 25 alone which is printed.

Example Use/Output

$ sed -n '/^[[:space:]]*var3=/s/^[^=]*=//p' file
25

Upvotes: 2

Related Questions