fork download
  1. digit_to_word() {
  2. case $1 in
  3. 4) echo "four" ;;
  4. 10) echo "ten" ;;
  5. 14) echo "fourteen" ;;
  6. *) echo "$1" ;;
  7. esac
  8. }
  9.  
  10. write_input() {
  11. cat <<'EOF'
  12. I have two apples
  13. He has 4 apples
  14. They have 10 pizzas
  15. 4 score and 14 years ago
  16. EOF
  17. }
  18.  
  19. regex='([[:space:]])([0-9]+)([[:space:]])'
  20.  
  21. write_input |
  22. while IFS= read -r line; do
  23. line=" ${line} " # pad with space so first and last words work consistently
  24. while [[ $line =~ $regex ]]; do # loop while at least one replacement is pending
  25. pre_space=${BASH_REMATCH[1]} # whitespace before the word, if any
  26. word=${BASH_REMATCH[2]} # actual word to replace
  27. post_space=${BASH_REMATCH[3]} # whitespace after the word, if any
  28. replace=$(digit_to_word "$word") # new word to use
  29. in=${pre_space}${word}${post_space} # old word padded with whitespace
  30. out=${pre_space}${replace}${post_space} # new word padded with whitespace
  31. line=${line//$in/$out} # replace old w/ new, keeping whitespace
  32. done
  33. line=${line#' '}; line=${line%' '} # remove the padding we added earlier
  34. printf '%s\n' "$line" # write the output line
  35. done
Success #stdin #stdout 0s 19672KB
stdin
Standard input is empty
stdout
I have two apples
He has four apples 
They have ten pizzas
four score and fourteen years ago