如何使用 Eclipse 或 PowerGREP 搜索和替换文件中的块?

how to search and replace a block in files with Eclipse or PowerGREP?

我的文件开头有一个 read me 部分,很多文件。该部分的格式如下:

###############   Read me ###############

many lines here

########################################

我想用新内容更新它们。我正在使用 Windows 7 但可以访问 Linux。我有 EclipsePowerGREP。我不知道如何使用 OS 命令行命令来执行此操作,也不知道如何使用 Eclipse 或 PowerGREP 来执行此操作。有人可以帮我解决这个问题吗?

如果您的部分格式始终相同,应该像这样简单:

###############   Read me ###############[\s\S]*?########################################

使用内联 (?s) single-line/dot-matches-all 模式,您可以使用常规 . 而不是 [\s\S] 但这并不重要。见 Demo.

然后,根据需要替换文本块。

您可以使用 awk

轻松完成

输入:

###############   Read me ###############

many lines here
many lines here
many lines here

########################################
real stuff
real stuff
real stuff
real stuff
###############   Read me ###############

many lines here
many lines here
many lines here
blabla

########################################
real stuff2
real stuff2
real stuff2

命令:

awk '/######   Read me #####/{a=0}/^#+$/{a=1;next}{if(a)print}' input
real stuff
real stuff
real stuff
real stuff
real stuff2
real stuff2
real stuff2

您只需要将输出重定向到另一个文件。

解释:

  • /###### Read me #####/{a=0} 当行包含 ###### Read me ##### 时将变量放在 0
  • /^#+$/{a=1;next} 当一行仅包含 # 时将该变量放回 1
  • {if(a)print} 当变量位于 1 时打印行