从字符串中查找并替换大写字符并保留原始匹配

Find and replace an uppercase character from a string and keep the original match

我需要将字符串 "TestString" 更改为这种格式“[tT]est[sS]tring”。

我尝试使用 sed:

testString="TestString" sed 's/\([[:upper:]]\)/[&]/g' <<< "$testString" | tr '[[:upper:]]' '[[:lower:]]'

结果是: [tt]est[ss]tring

我想请你帮忙想办法让括号内的第二个字符大写。

谢谢。

您可以只使用 sed 而不必使用 tr。以下适用于 GNU

的版本
sed -E 's/([[:upper:]])/[\L\u&]/g' <<< "$testString"

了解其工作原理

s/([[:upper:]])/[\L\u&]/g
#  ^^^^^^^^^^^              Match the uppercase character
#                ^^^^       lower case the matched letter
#                    ^^^^   upper case the matched letter

您也可以执行 s/([[:upper:]])/[\L\u]/g,因为 </code> 和 <code>& 都指的是搜索模式中的匹配组。

MacOS (FreeBSD) sed 默认不支持大小写转换函数\L\u。您可以使用 brew install gnu-sed 安装它并调用 gsed 来启动它。