How to convert a string to lower case in Bash?

前端 未结 20 2405
慢半拍i
慢半拍i 2020-11-22 09:40

Is there a way in bash to convert a string into a lower case string?

For example, if I have:

a=\"Hi all\"

I want to convert it to:<

20条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 10:02

    In spite of how old this question is and similar to this answer by technosaurus. I had a hard time finding a solution that was portable across most platforms (That I Use) as well as older versions of bash. I have also been frustrated with arrays, functions and use of prints, echos and temporary files to retrieve trivial variables. This works very well for me so far I thought I would share. My main testing environments are:

    1. GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)
    2. GNU bash, version 3.2.57(1)-release (sparc-sun-solaris2.10)
    lcs="abcdefghijklmnopqrstuvwxyz"
    ucs="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    input="Change Me To All Capitals"
    for (( i=0; i<"${#input}"; i++ )) ; do :
        for (( j=0; j<"${#lcs}"; j++ )) ; do :
            if [[ "${input:$i:1}" == "${lcs:$j:1}" ]] ; then
                input="${input/${input:$i:1}/${ucs:$j:1}}" 
            fi
        done
    done
    

    Simple C-style for loop to iterate through the strings. For the line below if you have not seen anything like this before this is where I learned this. In this case the line checks if the char ${input:$i:1} (lower case) exists in input and if so replaces it with the given char ${ucs:$j:1} (upper case) and stores it back into input.

    input="${input/${input:$i:1}/${ucs:$j:1}}"
    

提交回复
热议问题