Convert CamelCase to lowerCamelCase with POSIX Shell

I am trying to change only the first letter of a lowercase string using a shell script. Ideally, an easy way to go from CamelCase to lowerCamelCase.

TASK:

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

I found some great resources for this for the entire line , but did not just change the first letter and left the remaining line untouched.

+5
source share
6 answers

If your shell is fairly recent, you can use the following parameter extension:

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

Alternative solution (will work with old bash too)

 DIR="SomeString" echo $(echo ${DIR:0:1} | tr "[AZ]" "[az]")${DIR:1} 

prints

 someString 

to define a variable

 DIR2="$(echo ${DIR:0:1} | tr "[AZ]" "[az]")${DIR:1}" echo $DIR2 

prints

 someString 

alternate 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 decisions;

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

All of the above is verified using OSX /bin/bash .

+4
source

With sed:

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

^ means start of line \L - command to make a lowercase match & - this is a complete match

+3
source

Perl Solution:

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

Since awk is not mentioned yet, here you can do another way (GNU awk is required):

 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. 1 at the end prints a line. If your shell does not support <<< , you can do echo "$dir" | awk ... echo "$dir" | awk ... instead.

+2
source

If you are looking for a POSIX compatible solution, check out the typeset .

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

Conclusion:

 someString 

The typeset command creates a special variable that has string values, left justification, and one long char. ${var#?} truncates the first occurrence of the pattern from the beginning of $var and ? corresponds to one character.

-1
source

Source: https://habr.com/ru/post/1201856/


All Articles