Skip to content

Instantly share code, notes, and snippets.

@shollingsworth
Created December 21, 2017 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shollingsworth/2318499964e419aabc4bc038adb061f8 to your computer and use it in GitHub Desktop.
Save shollingsworth/2318499964e419aabc4bc038adb061f8 to your computer and use it in GitHub Desktop.
convert duration string like: 2d3h5m30s into seconds only (bash)
#!/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