Issue
I have a YAML file composed of the following:
acceleration_matrix:
# 1ere row: x
- [20, 0, 0, 15, 15]
# 2eme row: y
- [0, 15, 0, 0, 0]
# 3eme row: z
- [0, 0, 30, 15, -15]
# 4eme row: repere de l'acceleration
- [0, 0, 0, 0, 0]
# 5eme row: loadcase_id
- [1, 2, 3, 4, 5]
I want to extract the last value of the last row (in this case, 5
) unsing a shell script.
Using this article, I coded:
#!/bin/bash
function parse_yaml {
local prefix=$2
local s='[[:space:]]*' w='[a-zA-Z0-9_]*' fs=$(echo @|tr @ '\034')
sed -ne "s|^\($s\):|\1|" \
-e "s|^\($s\)\($w\)$s:$s[\"']\(.*\)[\"']$s\$|\1$fs\2$fs\3|p" \
-e "s|^\($s\)\($w\)$s:$s\(.*\)$s\$|\1$fs\2$fs\3|p" $1 |
awk -F$fs '{
indent = length($1)/2;
vname[indent] = $2;
for (i in vname) {if (i > indent) {delete vname[i]}}
if (length($3) > 0) {
vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
printf("%s%s%s=\"%s\"\n", "'$prefix'",vn, $2, $3);
}
}'
}
parse_yaml nastran_acceleration_matrix.yml
echo $acceleration_matrix
But as I am a newbie in shell, I can't find how to extract the values. What I would want is simply something like :
set number_load_case = ### acceleration_matrix[-1,-1] ### (I'm more used to coding in python thus the -1 aka last row/column)
Could anybody help me out?
Thanks in advance!
Solution
I'd recommend using a proper parser such as yq. Your task (last value of last element of acceleration_matrix
) then becomes as simple as
yq eval '.acceleration_matrix[-1][-1]' nastran_acceleration_matrix.yml
Answered By - Benjamin W.