Skip to content

Instantly share code, notes, and snippets.

@ewe2
Forked from pysysops/number2roman.sh
Created August 14, 2019 01:42
Show Gist options
  • Save ewe2/887d7dcbd02530bebb8c08baea6d8091 to your computer and use it in GitHub Desktop.
Save ewe2/887d7dcbd02530bebb8c08baea6d8091 to your computer and use it in GitHub Desktop.
Convert numbers to Roman numerals
#!/bin/bash
set -eu -o pipefail
number=$1
# Test that it is valid
[[ "${number//[0-9]/}" == "" ]] || \
{ echo Number ${number} contains invalid characters ; \
exit 1 ;}
# First we convert the number to a Roman Numeral unary representation
# then we replace appropriate chunks of tokens and end up with a Roman Numeral
# representation.
roman_numerals=$(
printf "%.sI" $(seq 1 ${number}) |
sed 's/IIIII/V/g' |
sed 's/IIII/IV/g' |
sed 's/VV/X/g' |
sed 's/VIV/IX/g' |
sed 's/XXXXX/L/g' |
sed 's/XXXX/XL/g' |
sed 's/LL/C/g' |
sed 's/LXL/XC/g' |
sed 's/CCCCC/D/g' |
sed 's/CCCC/CD/g' |
sed 's/DD/M/g' |
sed 's/DCD/CM/g'
)
echo ${number} is ${roman_numerals}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment