job.answiz.com
  • 0
Votes
name
name Punditsdkoslkdosdkoskdo

How to convert a string to lower case in Bash?

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

For example, if I have:

a="Hi all"

I want to convert it to:

"hi all"

The are various ways:

POSIX standard

tr

$ echo "$a" | tr '[:upper:]' '[:lower:]'
hi all

AWK

$ echo "$a" | awk '{print tolower($0)}'
hi all

Non-POSIX

You may run into portability issues with the following examples:

Bash 4.0

$ echo "${a,,}"
hi all

sed

$ echo "$a" | sed -e 's/(.*)/L/'
hi all
# this also works:
$ sed -e 's/(.*)/L/' <<< "$a"
hi all

Perl

$ echo "$a" | perl -ne 'print lc'
hi all

Bash

lc(){
    case "$1" in
        [A-Z])
        n=$(printf "%d" "'$1")
        n=$((n+32))
        printf \$(printf "%o" "$n")
        ;;
        *)
        printf "%s" "$1"
        ;;
    esac
}
word="I Love Bash"
for((i=0;i<${#word};i++))
do
    ch="${word:$i:1}"
    lc "$ch"
done
  • 0
Reply Report