Last active
February 8, 2020 07:53
-
-
Save rawiriblundell/7b6914a11d3fdcdbd9aebc45fd38b4a1 to your computer and use it in GitHub Desktop.
Pure bash tolower example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| if (( BASH_VERSINFO >= 4 )); then | |
| tolower() { | |
| # If parameter is a file, or stdin is used, action that first | |
| if [[ -r "${1}" ]]||[[ ! -t 0 ]]; then | |
| # We structure our while read loop to handle no newline at EOF | |
| eof= | |
| while [[ -z "${eof}" ]]; do | |
| read -r || eof=true | |
| printf -- '%s\n' "${REPLY,,}" | |
| done < "${1:-/dev/stdin}" | |
| # Otherwise, if a parameter exists, modify it | |
| elif [[ "${1}" ]]; then | |
| printf -- '%s\n' "${*,,}" | |
| # Otherwise we print our usage | |
| else | |
| printf -- '%s\n' "Usage: tolower [FILE|STDIN|STRING]" | |
| return 1 | |
| fi | |
| } | |
| else | |
| # This is the magic sauce - we convert the input character to a decimal (%d) | |
| # Then add 32 to move it 32 places on the ASCII table | |
| # Then we print it in unsigned octal (%o) | |
| # And finally print the char that matches the octal representation (\\) | |
| # Example: printf '%d' "'A" => 65 (+32 = 97) | |
| # printf '%o' "97" => 141 | |
| # printf \\141 => a | |
| lc(){ | |
| # shellcheck disable=SC2059 | |
| case "${1}" in | |
| ([[:upper:]]) | |
| printf \\"$(printf '%o' "$(( $(printf '%d' "'${1}") + 32 ))")" | |
| ;; | |
| (*) | |
| printf "%s" "${1}" | |
| ;; | |
| esac | |
| } | |
| tolower() { | |
| if [[ -r "${1}" ]]||[[ ! -t 0 ]]; then | |
| eof= | |
| while [[ -z "${eof}" ]]; do | |
| read -r || eof=true | |
| for ((i=0;i<${#REPLY};i++)); do | |
| lc "${REPLY:$i:1}" | |
| done | |
| printf -- '%s\n' "" | |
| done < "${1:-/dev/stdin}" | |
| elif [[ "${1}" ]]; then | |
| output="$*" | |
| for ((i=0;i<${#output};i++)); do | |
| lc "${output:$i:1}" | |
| done | |
| printf -- '%s\n' "" | |
| else | |
| printf -- '%s\n' "Usage: tolower [FILE|STDIN|STRING]" | |
| return 1 | |
| fi | |
| } | |
| fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment