Monday, October 24, 2022

[SOLVED] Extracting different types of data from a file and save these values in variables

Issue

I have a file like

water
{
    nu              1.69e-3;
    rho             8;
}
vapour
{
    rho             2;
}
right
{
    type            zeroGradient 6;
    value           uniform (40 10 0);  

}

left
{
    value           uniform (0 5 0);    
}

and I want to extract the values 1.69e-3, 8,2, 40, 5 from it and save these values in variables separately. To extract 8 and 2 and save them in variables I use the following commands,

rhol=`grep rho file | awk '{print $NF}' | sed -e 's/;//g' | head -1`
rhog=`grep -m2 rho file | awk '{print $NF}' | sed -e 's/;//g' | tail -n1`

But to get the scientific value of 1.69e-3, and two other values 40 and 5 I have problem to get the values.


Solution

Here's a simple Awk parser which outputs assignments you can eval. You will want to make very sure the output is what you expect before you actually do that.

awk 'BEGIN { insec=0 }
/[^{]/ && NF==1 && !insec { sec=$1; next }
/[{]/ && sec { insec=1; next }
/[}]/ && insec { sec=""; insec=0; next }
insec && !/^[ \t]*(value|type)/ && NF>1 { sub(/;$/, ""); printf "%s_%s=%s\n", sec, $1, $NF }
insec && /^[ \t]*value/ { gsub(/[();]+/, ""); for(i=3; i<=NF; i++) printf "%s_%i=%s\n", sec, i-2, $i }' "$@"

Save this as a script; running it on the file should produce something like

water_nu=1.69e-3
water_rho=8
vapour_rho=2
right_1=40
right_2=10
right_3=0
left_1=0
left_2=5
left_3=0

As requested in a comment, this splits up the uniform fields into separate values left_1, left_2 etc. (But really, please make sure your question itself is complete and well-defined. Comments could be deleted at any time.)

Once the results are what you want, you'd run it like

eval "$(yourscript yourfile)"

to have the shell evaluate the assignments it outputs.

Demo: https://ideone.com/hGPsTE

As ever, be very paranoid before actually using eval. There is probably a much better way to do what you ask; I would suggest implementing the rest of the logic in Awk too if feasible.



Answered By - tripleee
Answer Checked By - Katrina (WPSolving Volunteer)