【问题标题】:Find and replace string with regex用正则表达式查找和替换字符串
【发布时间】:2021-05-18 18:26:27
【问题描述】:

这可能是一个新手正则表达式问题(仍在学习),但我正在尝试取消我代码中所有对象的大写(但不是类);即代码sn-p:

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 的原因。

【问题讨论】:

  • 使用 sed 时,您可以将 [;.] 与捕获组匹配,并将匹配到的任何内容返回到输出的相同位置。

标签: regex linux unix sed


【解决方案1】:

你可以使用

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()...

【讨论】:

  • 这行得通。我知道解决方案是\1 部分。谢谢!
  • (和\([;.]\)的变化为查找)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-22
  • 1970-01-01
  • 2016-08-16
  • 2014-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多