Simple TextWrangler Grep Replace

Edward Pacino picture Edward Pacino · Feb 2, 2012 · Viewed 36.6k times · Source

I am trying to replace all h2 tags containing the class "title" with h1:

<h2 class="title">Things</h2>

I'm using the Multi-File search in TextWranger with this:

<h2 class="title">[^>]*</h2>

I'm able to find everything, but when I hit replace, it replaces my titles with the grep crap.

BEFORE: <h2 class="title">Things</h2>
AFTER:    <h1 class="title">[^>]*</h1>

My problem is that the search not only replaces my tags but also replaces my content with [^>]*. I also tried this in Aptana and the same thing happened. I would appreciate some insight.

Answer

mathematical.coffee picture mathematical.coffee · Feb 2, 2012

It looks like you're converting <h2 class="title"> to h1? You have to use a backreference in your "replace":

Search: <h2 class="title">([^>]*)</h2>

Replace: <h1 class="title">\1</h1> (aside- if it's a h1 do you still want to preserve the 'class="title"'?)

Note the brackets in the search regex, which save what's inside them.

Then you use \1 to pull them back out in the replace text (\1 for the first set of brackets, \2 for the second, ... )