我想用bash将字符串中的第一个字符大写。

foo="bar";

//uppercase first character

echo $foo;

应打印“Bar”;


当前回答

它也可以在纯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}"

其他回答

这也可以……

FooBar=baz

echo ${FooBar^^${FooBar:0:1}}

=> Baz
FooBar=baz

echo ${FooBar^^${FooBar:1:1}}

=> bAz
FooBar=baz

echo ${FooBar^^${FooBar:2:2}}

=> baZ

等等。

来源:

Bash手动:Shell参数扩展 完整Bash指南:参数 Bash黑客的维基参数扩展

入门/教程:

Cyberciti.biz: 8。转换为大写到小写或反之亦然 Opensource.com: Bash中参数展开的介绍

这个对我很有用:

搜索当前目录下的所有*php文件,并将每个文件名的第一个字符替换为大写字母:

例如:test.php => test.php

for f in *php ; do mv "$f" "$(\sed 's/.*/\u&/' <<< "$f")" ; done

仅使用awk

foo="uNcapItalizedstrIng"
echo $foo | awk '{print toupper(substr($0,0,1))tolower(substr($0,2))}'

如果第一个字符不是字母(而是制表符、空格和转义双引号)怎么办?我们最好测试它,直到我们找到一个字母!所以:

S='  \"ó foo bar\"'
N=0
until [[ ${S:$N:1} =~ [[:alpha:]] ]]; do N=$[$N+1]; done
#F=`echo ${S:$N:1} | tr [:lower:] [:upper:]`
#F=`echo ${S:$N:1} | sed -E -e 's/./\u&/'` #other option
F=`echo ${S:$N:1}
F=`echo ${F} #pure Bash solution to "upper"
echo "$F"${S:(($N+1))} #without garbage
echo '='${S:0:(($N))}"$F"${S:(($N+1))}'=' #garbage preserved

Foo bar
= \"Foo bar=

使用bash(版本4+)的一种方法:

foo=bar
echo "${foo^}"

打印:

Bar