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

foo="bar";

//uppercase first character

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 -选择剪贴板 }

其他回答

$ foo="bar";
$ foo=`echo ${foo:0:1} | tr  '[a-z]' '[A-Z]'`${foo:1}
$ echo $foo
Bar

Posix兼容,子进程更少:

v="foo[Bar]"
printf "%s" "${v%"${v#?}"}" | tr '[:lower:]' '[:upper:]' && printf "%s" "${v#?}"
==> Foo[Bar]

只大写第一个单词:

foo='one two three'
foo="${foo^}"
echo $foo

一二三


将变量中的每个单词大写:

foo="one two three"
foo=( $foo ) # without quotes
foo="${foo[@]^}"
echo $foo

一二三


(适用于bash 4+)

使用sed的一种方法:

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

打印:

Bar

下面是“原生”文本工具的使用方法:

#!/bin/bash

string="abcd"
first=`echo $string|cut -c1|tr [a-z] [A-Z]`
second=`echo $string|cut -c2-`
echo $first$second