这可能是一个新手正则表达式问题(仍在学习),但我正在尝试将代码中的所有对象(但不是类)大写;即代码片段:
Bishop_Piece Bishop;
Bishop.move()...
我希望它是:
Bishop_Piece bishop;
bishop.move()...
我尝试过的:
find . -type f | xargs sed -i 's/Bishop[;.]/bishop./g'
但是这会导致:
Bishop_Piece bishop.
bishop.move()...
基本上,我希望我要搜索的字符(即 Bishop)被“保留”(无论是 ;
或 .
),即bishop./g
.
最佳答案
你可以使用
find . -type f | xargs sed -i 's/Bishop\([;.]\)/bishop\1/g'
请注意,此处的 \([;.]\)
定义了一个捕获组,其值由替换模式中的 \1
引用。
(...)
括号被转义,因为这是符合 POSIX BRE 的正则表达式。
请参阅online demo :
s='Bishop_Piece bishop;
bishop.move()...'
sed 's/Bishop\([;.]\)/bishop\1/g' <<< "$s"
输出:
Bishop_Piece bishop;
bishop.move()...
关于regex - 使用正则表达式查找并替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66215290/