我想用bash将字符串中的第一个字符大写。
foo="bar";
//uppercase first character
echo $foo;
应打印“Bar”;
我想用bash将字符串中的第一个字符大写。
foo="bar";
//uppercase first character
echo $foo;
应打印“Bar”;
当前回答
只大写第一个单词:
foo='one two three'
foo="${foo^}"
echo $foo
一二三
将变量中的每个单词大写:
foo="one two three"
foo=( $foo ) # without quotes
foo="${foo[@]^}"
echo $foo
一二三
(适用于bash 4+)
其他回答
这里只是为了好玩:
foo="bar";
echo $foo | awk '{$1=toupper(substr($1,0,1))substr($1,2)}1'
# or
echo ${foo^}
# or
echo $foo | head -c 1 | tr [a-z] [A-Z]; echo $foo | tail -c +2
# or
echo ${foo:1} | sed -e 's/^./\B&/'
Linux和OSX的另一种干净的解决方案,它也可以与bash变量一起使用
python -c "print(\"abc\".capitalize())"
返回美国广播公司
$ foo="bar";
$ foo=`echo ${foo:0:1} | tr '[a-z]' '[A-Z]'`${foo:1}
$ echo $foo
Bar
下面是“原生”文本工具的使用方法:
#!/bin/bash
string="abcd"
first=`echo $string|cut -c1|tr [a-z] [A-Z]`
second=`echo $string|cut -c2-`
echo $first$second
它也可以在纯bash中使用bash-3.2完成:
# First, get the first character.
fl=${foo:0:1}
# Safety check: it must be a letter :).
if [[ ${fl} == [a-z] ]]; then
# Now, obtain its octal value using printf (builtin).
ord=$(printf '%o' "'${fl}")
# Fun fact: [a-z] maps onto 0141..0172. [A-Z] is 0101..0132.
# We can use decimal '- 40' to get the expected result!
ord=$(( ord - 40 ))
# Finally, map the new value back to a character.
fl=$(printf '%b' '\'${ord})
fi
echo "${fl}${foo:1}"