
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
一般的な形式は、大文字と小文字を反転する文字の位置 (0 から始まるインデックス) です
substr($_,n,1)
。n
ASCII 文字とスペースを XOR すると、大文字と小文字が反転します。