haysclark
haysclark

Reputation: 1080

Converting CamelCase to lowerCamelCase with POSIX Shell

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.

Upvotes: 6

Views: 2200

Answers (6)

clt60
clt60

Reputation: 63892

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.

Upvotes: 4

jaypal singh
jaypal singh

Reputation: 77075

If you are looking for a POSIX compliant solution then have a look at typeset.

var='SomeString'
typeset -lL1 b="$var"
echo "${b}${var#?}"

Output:

someString

The typeset command creates a special variable that is lowercase, left aligned and one char long. ${var#?} trims the first occurrence of pattern from the start of $var and ? matches a single character.

Upvotes: -1

Tom Fenech
Tom Fenech

Reputation: 74596

Since awk hasn't yet been mentioned, here's another way you could do it (requires GNU awk):

dir="SomeString"
new_dir=$(awk 'BEGIN{FS=OFS=""}{$1=tolower($1)}1' <<<"$dir")

This sets the input and output field separators to an empty string, so each character is a field. The tolower function does what you think it does. 1 at the end prints the line. If your shell doesn't support <<< you can do echo "$dir" | awk ... instead.

Upvotes: 2

choroba
choroba

Reputation: 241738

Perl solution:

DIR=SomeString
perl -le 'print lcfirst shift' "$DIR"

Upvotes: 2

choroba
choroba

Reputation: 241738

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

DIR="SomeString"   # Note the missing dollar sign.
echo ${DIR,}

Upvotes: 6

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

With sed:

var="SomeString"
echo $var | sed 's/^./\L&/'

^ means the start of the line \L is the command to make the match in lowercase & is the whole match

Upvotes: 3

Related Questions