Skip to content

Instantly share code, notes, and snippets.

@ewe2
Forked from pysysops/roman2number.sh
Created August 14, 2019 01:42
Show Gist options
  • Save ewe2/a96bfa36614ba03e2a193f7449471577 to your computer and use it in GitHub Desktop.
Save ewe2/a96bfa36614ba03e2a193f7449471577 to your computer and use it in GitHub Desktop.
Convert roman numerals to a number in BASH
#!/bin/bash
set -eu -o pipefail
roman_numerals=$(echo $1 | tr a-z A-Z)
# Test that it is valid
[[ "${roman_numerals//[IVXLCDM]/}" == "" ]] || \
{ echo Roman numerals ${roman_numerals} contains invalid characters ; \
exit 1 ;}
# We want to replace all tokens to eventually have
# all I's, remove new lines and count the characters.
number=$(
echo ${roman_numerals} |
sed 's/CM/DCD/g' |
sed 's/M/DD/g' |
sed 's/CD/CCCC/g' |
sed 's/D/CCCCC/g' |
sed 's/XC/LXL/g' |
sed 's/C/LL/g' |
sed 's/XL/XXXX/g' |
sed 's/L/XXXXX/g' |
sed 's/IX/VIV/g' |
sed 's/X/VV/g' |
sed 's/IV/IIII/g' |
sed 's/V/IIIII/g' |
tr -d '\n' |
wc -m
)
echo ${roman_numerals} is ${number}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment