Skip to content

Instantly share code, notes, and snippets.

@pysysops
Last active June 25, 2023 18:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pysysops/7596f1c0a5c6d14151bbd987a2fb95e5 to your computer and use it in GitHub Desktop.
Save pysysops/7596f1c0a5c6d14151bbd987a2fb95e5 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}
@Wanikoko
Copy link

ty so much :)

Copy link

ghost commented Jan 22, 2021

Thanks

@nickbailey
Copy link

Just what I needed! Thanks!

I have written a version as a bash function which does some more input validation (so numbers like IVI report an error). It's here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment