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

foo="bar";

//uppercase first character

echo $foo;

应打印“Bar”;


当前回答

这里只是为了好玩:

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&/'

其他回答

虽然不是我要求的,但很有帮助

declare -u foo #When the variable is assigned a value, all lower-case characters are converted to upper-case.

foo=bar
echo $foo
BAR

反之亦然

declare -l foo #When the variable is assigned a value, all upper-case characters are converted to lower-case.

foo=BAR
echo $foo
bar
first-letter-to-lower () {
        str="" 
        space=" " 
        for i in $@
        do
                if [ -z $(echo $i | grep "the\|of\|with" ) ]
                then
                        str=$str"$(echo ${i:0:1} | tr  '[A-Z]' '[a-z]')${i:1}$space" 
                else
                        str=$str${i}$space 
                fi
        done
        echo $str
}
first-letter-to-upper-xc () {
        v-first-letter-to-upper | xclip -selection clipboard
}
first-letter-to-upper () {
        str="" 
        space=" " 
        for i in $@
        do
                if [ -z $(echo $i | grep "the\|of\|with" ) ]
                then
                        str=$str"$(echo ${i:0:1} | tr  '[a-z]' '[A-Z]')${i:1}$space" 
                else
                        str=$str${i}$space 
                fi
        done
        echo $str
}

first-letter-to-lower-xc () { v首字母到下| xclip -选择剪贴板 }

使用sed的一种方法:

echo "$(echo "$foo" | sed 's/.*/\u&/')"

打印:

Bar

据我所知,这是POSIX sh兼容的。

upper_first.sh:

#!/bin/sh

printf "$1" | cut -c1 -z | tr -d '\0' | tr [:lower:] [:upper:]
printf "$1" | cut -c2-

Cut -c1 -z以\0而不是\n结束第一个字符串。它被tr -d '\0'删除。它也可以省略-z并使用tr -d '\n'来代替,但如果字符串的第一个字符是换行符,则会中断。

用法:

$ upper_first.sh foo
Foo
$

在函数中:

#!/bin/sh

function upper_first ()
{
    printf "$1" | cut -c1 -z | tr -d '\0' | tr [:lower:] [:upper:]
    printf "$1" | cut -c2-
}

old="foo"
new="$(upper_first "$old")"
echo "$new"

仅使用awk

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