how to use grep, sed, and awk to parse tags?

0

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?

Ritwik Bose

Posted 2010-02-01T20:27:31.213

Reputation: 828

2

Let's hope it's not HTML tags: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags :)

– John T – 2010-02-01T20:34:09.933

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 – Ritwik Bose – 2010-02-01T20:37:36.570

Answers

1

In awk:

START                  {noprefix="true"}
/<close tag regex>/    {noprefix="true"}
noprefix=="false"      {print "prefix", $0}
noprefix=="true"       {print $0}
/<open tag regex>/     {noprefix="false"}

mpez0

Posted 2010-02-01T20:27:31.213

Reputation: 2 578

Perfect. Now, my only other question is: is it possible for an awk script to take arguments? :-p – Ritwik Bose – 2010-02-01T21:37:52.017

Yes, check out http://www.math.utah.edu/docs/info/gawk_15.html#SEC136

– DCookie – 2010-02-01T22:05:16.183

Also, http://evc-cit.info/cit052/pass_to_awk.html

– DCookie – 2010-02-01T22:14:21.747

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 http://www.shelldorado.com/goodcoding/awkinvoke.html#shcall.

– mpez0 – 2010-02-02T14:07:43.163

1

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

9tat

Posted 2010-02-01T20:27:31.213

Reputation: 21

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. – Ritwik Bose – 2010-02-08T14:34:31.583

0

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.

0fnt

Posted 2010-02-01T20:27:31.213

Reputation: 1 741

apparently, not true. – Ritwik Bose – 2010-02-01T21:42:22.147