bash 变量中的第一个大写字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12487424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
uppercase first character in a variable with bash
提问by chovy
I want to uppercase just the first character in my string with bash.
我想用 bash 将字符串中的第一个字符大写。
foo="bar";
//uppercase first character
echo $foo;
should print "Bar";
应该打印“酒吧”;
采纳答案by Michael Hoffman
foo="$(tr '[:lower:]' '[:upper:]' <<< ${foo:0:1})${foo:1}"
回答by Steve
One way with bash (version 4+):
使用 bash 的一种方式(版本 4+):
foo=bar
echo "${foo^}"
prints:
印刷:
Bar
回答by Steve
One way with sed
:
一种方式sed
:
echo "$(echo "$foo" | sed 's/.*/\u&/')"
Prints:
印刷:
Bar
回答by Majid Laissi
$ foo="bar";
$ foo=`echo ${foo:0:1} | tr '[a-z]' '[A-Z]'`${foo:1}
$ echo $foo
Bar
回答by Equin0x
Here is the "native" text tools way:
这是“本机”文本工具方式:
#!/bin/bash
string="abcd"
first=`echo $string|cut -c1|tr [a-z] [A-Z]`
second=`echo $string|cut -c2-`
echo $first$second
回答by toske
Using awk only
仅使用 awk
foo="uNcapItalizedstrIng"
echo $foo | awk '{print toupper(substr(# 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}"
,0,1))tolower(substr(FooBar=baz
echo ${FooBar^^${FooBar:0:1}}
=> Baz
,2))}'
回答by Micha? Górny
It can be done in pure bash with bash-3.2 as well:
它也可以使用 bash-3.2 在纯 bash 中完成:
FooBar=baz
echo ${FooBar^^${FooBar:1:1}}
=> bAz
回答by zetaomegagon
This works too...
这也有效...
FooBar=baz
echo ${FooBar^^${FooBar:2:2}}
=> baZ
foo='one two three'
foo="${foo^}"
echo $foo
foo="one two three"
foo=( $foo ) # without quotes
foo="${foo[@]^}"
echo $foo
And so on.
等等。
Sources:
资料来源:
- Bash Manual: Shell Parameter Expansion
- Full Bash Guide: Parameters
- Bash Hacker's Wiki Parameter Expansion
- Bash 手册:Shell 参数扩展
- 完整的 Bash 指南:参数
- Bash Hacker 的 Wiki参数扩展
Inroductions/Tutorials:
介绍/教程:
- Cyberciti.biz: 8. Convert to upper to lower case or vice versa
- Opensource.com: An introduction to parameter expansion in Bash
- Cyberciti.biz:8 . 转换为大写或小写,反之亦然
- Opensource.com:Bash参数扩展介绍
回答by Wairua
To capitalize first word only:
仅将第一个单词大写:
python -c "print(\"abc\".capitalize())"
One two three
一二三
To capitalize every wordin the variable:
将变量中的每个单词大写:
##代码##One Two Three
ØNE牛逼WO牛逼重稀土
(works in bash 4+)
(适用于 bash 4+)
回答by Thomas Webber
Alternative and clean solution for both Linux and OSX, it can also be used with bash variables
适用于 Linux 和 OSX 的替代和干净的解决方案,它还可以与 bash 变量一起使用
##代码##returns Abc
返回ABC