Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting CamelCase to lowerCamelCase with POSIX Shell

Tags:

bash

shell

posix

I am trying to only change the first letter of a string to lowercase using a Shell script. Ideally a simple way to go from CamelCase to lowerCamelCase.

GOAL:

$DIR="SomeString"
# missing step
$echo $DIR
someString

I have found some great resources for doing this to the entire string but not just altering the first letter and leaving the remaining string untouched.

like image 413
haysclark Avatar asked Sep 04 '14 21:09

haysclark


2 Answers

If your shell is recent enough, you can use the following parameter expansion:

DIR="SomeString"   # Note the missing dollar sign.
echo ${DIR,}
like image 73
choroba Avatar answered Oct 02 '22 15:10

choroba


Alternative solution (will work on old bash too)

DIR="SomeString"
echo $(echo ${DIR:0:1} | tr "[A-Z]" "[a-z]")${DIR:1}

prints

someString

for assing to variable

DIR2="$(echo ${DIR:0:1} | tr "[A-Z]" "[a-z]")${DIR:1}"
echo $DIR2

prints

someString

alternative perl

DIR3=$(echo SomeString | perl -ple 's/(.)/\l$1/')
DIR3=$(echo SomeString | perl -nle 'print lcfirst')
DIR3=$(echo "$DIR"     | perl -ple 's/.*/lcfirst/e'

some terrible solutions;

DIR4=$(echo "$DIR" | sed 's/^\(.\).*/\1/' | tr "[A-Z]" "[a-z]")$(echo "$DIR" | sed 's/^.//')
DIR5=$(echo "$DIR" | cut -c1 | tr '[[:upper:]]' '[[:lower:]]')$(echo "$DIR" | cut -c2-)

All the above is tested with OSX's /bin/bash.

like image 26
jm666 Avatar answered Oct 02 '22 16:10

jm666