Reputation: 71
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
Reputation: 10113
A grep
one-liner, if your grep
has support for Perl-compatible regular expressions (the -P
option; not all grep
s 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 var3
s is a possibility.
Upvotes: 1
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
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,/find/
is all characters anchored from the '^'
beginning that are not the [^=]
character and then match the literal '='
character, and finally/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