大写第一个字符在一个variables与bash
我想大写,只是我的string中的第一个字符与bash。
foo="bar"; //uppercase first character echo $foo;
应打印“酒吧”;
foo="$(tr '[:lower:]' '[:upper:]' <<< ${foo:0:1})${foo:1}"
一种方法与bash:
foo=bar echo "${foo^}"
打印:
Bar
sed
一种方法:
echo "$(echo "$foo" | sed 's/.*/\u&/')"
打印:
Bar
$ foo="bar"; $ foo=`echo ${foo:0:1} | tr '[az]' '[AZ]'`${foo:1} $ echo $foo Bar
这里是“本地”文本工具的方式:
#!/bin/bash string="abcd" first=`echo $string|cut -c1|tr [az] [AZ]` second=`echo $string|cut -c2-` echo $first$second
它也可以在bash-3.2的纯粹bash中完成:
# First, get the first character. fl=${foo:0:1} # Safety check: it must be a letter :). if [[ ${fl} == [az] ]]; then # Now, obtain its octal value using printf (builtin). ord=$(printf '%o' "'${fl}") # Fun fact: [az] maps onto 0141..0172. [AZ] 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}"
仅使用awk
foo="uNcapItalizedstrIng" echo $foo | awk '{print toupper(substr($0,0,1))tolower(substr($0,2))}'
这个为我工作:
search当前目录中的所有* php文件,并将每个文件名的第一个字符replace为大写字母:
例如:test.php => Test.php
for f in *php ; do mv "$f" "$(\sed 's/.*/\u&/' <<< "$f")" ; done
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 '[AZ]' '[az]')${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 '[az]' '[AZ]')${i:1}$space" else str=$str${i}$space fi done echo $str }
first-letter-to-lower-xc(){v-first-letter-to-lower | xclip -selection剪贴板}
如果第一个字符不是一个字母(而是一个制表符,一个空格和一个转义双引号)呢? 我们最好testing一下, 直到find一封信! 所以:
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=