Created
December 21, 2017 19:09
-
-
Save shollingsworth/2318499964e419aabc4bc038adb061f8 to your computer and use it in GitHub Desktop.
convert duration string like: 2d3h5m30s into seconds only (bash)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
test_str="1h5m" | |
test_str="5d3h2m50v" #bad | |
test_str="5d3h2m50s" | |
declare -A keys | |
keys[d]=$((60 * 60 * 24)) | |
keys[h]=$((60 * 60)) | |
keys[m]=60 | |
keys[s]=1 | |
alphas=($(echo "${test_str}" | tr 'A-Z' 'a-z' | sed 's/[0-9]\+/\n/g' | sed '/^$/d')) | |
nums=($(echo "${test_str}" | tr 'A-Z' 'a-z' | sed 's/[a-z]\+/\n/g' | sed '/^$/d')) | |
val=0 | |
for i in "${!alphas[@]}"; do | |
metric=${alphas[${i}]} | |
echo ${!keys[@]} | grep -q "${metric}" || { | |
echo "Error, invalid metric: ${metric}, need ${!keys[@]}" | |
exit -1 | |
} | |
kv=${keys[${metric}]} | |
nv=${nums[${i}]} | |
val=$((${val} + (${kv} * ${nv}))) | |
done | |
echo "${val}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment