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

57 Views Asked by At

There is a read me section at the beginning of my files, many files. The section's format likes this:

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

many lines here

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

I want to update them with new contents. I am using Windows 7 but has access to Linux. I have Eclipse and also PowerGREP. I don't know how to do this with OS command line commands, and also don't know how to use Eclipse or PowerGREP to do this. Anybody can help me about this?

2

There are 2 best solutions below

2
wp78de On BEST ANSWER

If format of your sections is always the same, it should be as easy as this:

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

With an inline (?s) single-line/dot-matches-all mode you could use a regular . instead of [\s\S] but it doesn't matter much. See the Demo.

Then, replace the text block as needed.

0
Allan On

You can do it easily with awk

INPUT:

###############   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

command:

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

You just need to redirect the output to another file.

Explanations:

  • /###### Read me #####/{a=0} when the lines contain ###### Read me ##### put a variable at 0
  • /^#+$/{a=1;next} when a line contains only # put that variable back to 1
  • {if(a)print} when the variable is at 1 print the line