Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
2  
Let's hope it's not HTML tags: stackoverflow.com/questions/1732348/… :) –  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
add comment

3 Answers

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 math.utah.edu/docs/info/gawk_15.html#SEC136 –  DCookie Feb 1 '10 at 22:05
    
Also, evc-cit.info/cit052/pass_to_awk.html –  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 shelldorado.com/goodcoding/awkinvoke.html#shcall. –  mpez0 Feb 2 '10 at 14:07
add comment

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
add comment

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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.