
BASH
我想更改(或任何其他 *nix 工具,例如sed
、awk
、tr
等)中字串的第 n 個字母的大小寫。
我知道您可以使用以下命令更改整個字串的大小寫:
${str,,} # to lowercase
${str^^} # to uppercase
是否可以將“Test”的第3個字母的大小寫更改為大寫?
$ export str="Test"
$ echo ${str^^:3}
TeSt
答案1
在 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
在 Perl 中:
$ perl -ple 's/(?<=..)(.)/uc($1)/e; ' <<<$str
abCdefgh
或者
$ perl -ple 's/(..)(.)/$1.uc($2)/e; ' <<<$str
abCdefgh
答案2
使用 GNU sed
(可能是其他)
sed 's/./\U&/3' <<< "$str"
和awk
awk -vFS= -vOFS= '{$3=toupper($3)}1' <<< "$str"
答案3
其他perl
:
$ str="abcdefgh"
$ perl -pe 'substr($_,2,1) ^= " "' <<<"$str"
abCdefgh
一般形式是
substr($_,n,1)
wheren
是要反轉大小寫的字母位置(從 0 開始的索引)。當 ASCII 字元與空格進行異或時,會反轉其大小寫。