在bash gettng中,用大写字母替换的东西非常简单:
echo to_camel_case__variable | sed -r 's/(.)_+(.)/\1\U\2/g;s/^[a-z]/\U&/'
但是如果我不想更换怎么办?如果我只是想制作可变的pascal大小写而又保留下划线怎么办?
答案 0 :(得分:1)
这有效:
echo 'this_is_a_test' | sed 's/[^_]\+/\L\u&/g'
我会测试一下,但看起来很可靠。
答案 1 :(得分:1)
作为不依赖外部工具的纯bash实现(尽管需要现代bash 4.x):
case $BASH_VERSION in ''|[123].*) echo "ERROR: Bash 4.x+ required" >&2; exit 1;; esac
to_pascal_with_underscores() {
local s=${1^} re='(.*_+)([[:lower:]].*)' # initially capitalize 1st char
while [[ $s =~ $re ]]; do # match string $s against regex $re
s=${BASH_REMATCH[1]}${BASH_REMATCH[2]^} # capitalize first character of 2nd group
done
printf '%s\n' "$s" # avoid unreliable behavior associated w/ echo
}
to_pascal_with_underscores this_is_a_test
to_pascal_with_underscores to_camel_case__variable
...正确发射This_Is_A_Test
和To_Camel_Case__Variable
,如https://ideone.com/yen0T2