linux shell title case

2019-04-07 15:49发布

I am wrinting a shell script and have a variable like this: something-that-is-hyphenated.

I need to use it in various points in the script as:

something-that-is-hyphenated, somethingthatishyphenated, SomethingThatIsHyphenated

I have managed to change it to somethingthatishyphenated by stripping out - using sed "s/-//g".

I am sure there is a simpler way, and also, need to know how to get the camel cased version.

Edit: Working function derived from @Michał's answer

function hyphenToCamel {
    tr '-' '\n' | awk '{printf "%s%s", toupper(substr($0,1,1)), substr($0,2)}'
}

CAMEL=$(echo something-that-is-hyphenated | hyphenToCamel)
echo $CAMEL

Edit: Finally, a sed one liner thanks to @glenn

echo a-hyphenated-string | sed -E "s/(^|-)([a-z])/\u\2/g"

5条回答
做自己的国王
2楼-- · 2019-04-07 15:52

In the shell you are stuck with being messy:

   aa="aaa-aaa-bbb-bbb"
   echo " $aa" | sed -e 's/--*/ /g' -e 's/ a/A/g' -e 's/ b/B/g' ... -e 's/  *//g'

Note the carefully placed space in the echo and the double space in the last -e.

I leave it as an exercise to complete the code.

In perl it is a bit easier as a one-line shell command:

perl -e 'print map{ $a = ucfirst; $a =~ s/ +//g; $a} split( /-+/, $ARGV[0] ), "\n"' $aa
查看更多
叛逆
3楼-- · 2019-04-07 16:11

a GNU sed one-liner

echo something-that-is-hyphenated | 
sed -e 's/-\([a-z]\)/\u\1/g' -e 's/^[a-z]/\u&/'

\u in the replacement string is documented in the sed manual.

查看更多
一夜七次
4楼-- · 2019-04-07 16:12

For the records, here's a pure Bash safe method (that is not subject to pathname expansion)—using Bash≥4:

var0=something-that-is-hyphenated
IFS=- read -r -d '' -a var1 < <(printf '%s\0' "${var0,,}")
printf '%s' "${var1[@]^}"

This (safely) splits the lowercase expansion of var0 at the hyphens, with each split part in array var1. Then we use the ^ parameter expansion to uppercase the first character of the fields of this array, and concatenate them.

If your variable may also contain spaces and you want to act on them too, change IFS=- into IFS='- '.

查看更多
迷人小祖宗
5楼-- · 2019-04-07 16:13

You can define a function:

hypenToCamel() { 
    tr '-' '\n' | awk '{printf "%s%s", toupper(substr($0,0,1)), substr($0,2)}'
}

CAMEL=$(echo something-that-is-hyphenated | hypenToCamel)
echo $CAMEL
查看更多
▲ chillily
6楼-- · 2019-04-07 16:19

Pure bashism:

var0=something-that-is-hyphenated
var1=(${var0//-/ })
var2=${var1[*]^}
var3=${var2// /}
echo $var3
SomethingThatIsHyphenated

Line 1 is trivial.
Line 2 is the bashism for replaceAll or 's/-/ /g', wrapped in parens, to build an array.
Line 3 uses ${foo^}, which means uppercase (while ${foo,} would mean 'lowercase' [note, how ^ points up while , points down]) but to operate on every first letter of a word, we address the whole array with ${foo[*]} (or ${foo[@]}, if you would prefer that).
Line 4 is again a replace-all: blank with nothing.
Line 5 is trivial again.

查看更多
登录 后发表回答