Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to write a script that finds a open/close tag pair in a text file and prepends a fixed string to each line between the pair. I figure I use grep to find the tag line numbers and either awk or sed to place the tags, however, I'm not sure how exactly to do it.

Can someone help?

share|improve this question
Let's hope it's not HTML tags:… :) – John T Feb 1 '10 at 20:34
I'm thinking about something like if you put ;tag; <text> ;tag; then my program will go through and prepend tag to every line of <text>. I'm working on a note taking tool using markdown, but it's a pain to manually put a > on every line, or even > > :-p – mechko Feb 1 '10 at 20:37
up vote 1 down vote accepted

In awk:

START                  {noprefix="true"}
/<close tag regex>/    {noprefix="true"}
noprefix=="false"      {print "prefix", $0}
noprefix=="true"       {print $0}
/<open tag regex>/     {noprefix="false"}
share|improve this answer
Perfect. Now, my only other question is: is it possible for an awk script to take arguments? :-p – mechko Feb 1 '10 at 21:37
Yes, check out – DCookie Feb 1 '10 at 22:05
Also, – DCookie Feb 1 '10 at 22:14
To take arguments, you wrap the awk inside a shell script. A few minutes with a shell or awk programming book, or with Google, can find a lot of examples. A simple one is at – mpez0 Feb 2 '10 at 14:07

It should be done by one of the traditionally syntax aware languages (yacc etc). Doing it with grep and the like may be okay for specific cases but regexp simply is not powerful enough to catch the subtleties of HTML

share|improve this answer
actually, I got it to work just fine. I wrote a over awk in bash and stored the awk scripts as a text file. But it does everything I need it to do. – mechko Feb 8 '10 at 14:34

You should consider using yacc for it. It is NOT possible to do this with sed, awk or grep without a considerable amount of effort. As for learning yacc, it wouldn't take more time than it did for learning sed/awk/grep. And it will be really easy that way.

share|improve this answer
apparently, not true. – mechko Feb 1 '10 at 21:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .