I have a bashscript, which executes a command and calculates a pair of values, which output can look like this.

a,b (10.0000000000, 10.0000000000) -> volt (2088133.7088034691, -222653.3238934391)

And in case of invalid parameters or errors the program can show different error-messages.

Is there a safe way to parse the two volt-values and store them in two variables in a bash script?

Edit: Solution thanks to @jasonwryan and @KasiyA

variable=$([program call])

read var1 var2 <<< $(awk -F"[)(, ]" '{printf "%s\n%s\n", $(NF-3),$(NF-1)}' <<< "$variable")

echo "val1 = $var1"
echo "val2 = $var2"

Depends on how reliable the output is and what happens when you get the "different error messages", ie., how that would have to be handled.

A basic approach, with what you have above, you could use awk:

awk -F"[)(, ]" '{printf "var1=%s\nvar2=%s\n", $11,$13}'      

A "safe way" would depend on what those error messages do to the output...

As KasiyA points out, a more robust approach would be to use awk's built-in NF variable to calculate the relevant fields:

awk -F"[)(, ]" '{printf "var1=%s\nvar2=%s\n", $(NF-3),$(NF-1)}'
  • Thanks! That works great. The error messages are, if the parameters are invalid, either the help of the program or just text of the sort ("For the given a,b the voltage can't be calculated") or if some other data is missing "Failed to read file". – user3199134 Nov 8 '14 at 7:11
  • @user3199134 Well, you could test for the error string(s) and if they don't appear, parse the output for your variables. That would make it slightly "safer"... – jasonwryan Nov 8 '14 at 7:26
  • 1
    @jasonwryan Also it's better to use $(NF-3),$(NF-1) instead of $11,$13 because if the length of line is not fix then when you use $11,$13 may be it will be point to wrong index ;) – αғsнιη Nov 8 '14 at 7:41
  • Thanks! I edited it. And the simple safety is, if the error messages are put out by the program, awk fails (runtime error because negative field index) and var1 and var2 are empty, if they are, I know an error happened. It's not the safest and not the best solution, but it's still better than completely ignoring it. – user3199134 Nov 8 '14 at 7:50
  • 1
    @KasiyA That's an excellent suggestion: adding it. Thank you. – jasonwryan Nov 8 '14 at 7:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.