bashshellparameter-expansion

Bash convert last character to lower


I'm trying to convert the last character of in a variable to lower.

MY_STRING="THE_NAME_UPPER_A"

I want to change it by THE_NAME_UPPER_a. I've try this

MY_NEW_STRING="${MY_STRING,,A}"

but it changes all A to a, I just want to change the last one.


Solution

  • If I understand you correctly you could use tr:

    ## Your string
    MY_STRING="THE_NAME_UPPER_A"
    
    ## Everything but the last character
    prefix="${MY_STRING:0:$((${#MY_STRING}-1))}"
    
    ## Getting the last character
    lastChar="${MY_STRING: -1}"
    
    ## Change last character to lowercase
    lastCharLow="$(echo "$lastChar" | tr '[:upper:]' '[:lower:]')"
    
    ## Combine it all and echo
    echo "${prefix}${lastCharLow}"