rya*_*obs 9 shell bash sed string shell-script
我想换一个字符串的第n个字母的大小写BASH
(或任何其他的* nix工具,例如sed
,awk
,tr
等)。
我知道您可以使用以下方法更改整个字符串的大小写:
${str,,} # to lowercase
${str^^} # to uppercase
Run Code Online (Sandbox Code Playgroud)
是否可以将“Test”的第三个字母的大小写更改为大写?
$ export str="Test"
$ echo ${str^^:3}
TeSt
Run Code Online (Sandbox Code Playgroud)
使用 GNU sed
(可能是其他)
sed 's/./\U&/3' <<< "$str"
Run Code Online (Sandbox Code Playgroud)
和 awk
awk -vFS= -vOFS= '{$3=toupper($3)}1' <<< "$str"
Run Code Online (Sandbox Code Playgroud)
在 bash 你可以这样做:
$ str="abcdefgh"
$ foo=${str:2} # from the 3rd letter to the end
echo ${str:0:2}${foo^} # take the first three letters from str and capitalize the first letter in foo.
abCdefgh
Run Code Online (Sandbox Code Playgroud)
在 Perl 中:
$ perl -ple 's/(?<=..)(.)/uc($1)/e; ' <<<$str
abCdefgh
Run Code Online (Sandbox Code Playgroud)
或者
$ perl -ple 's/(..)(.)/$1.uc($2)/e; ' <<<$str
abCdefgh
Run Code Online (Sandbox Code Playgroud)