Formatting HTML options

One day I had a boring thing to do which in the end came an interesting one. So, I had a list of items and I had to format all these items in proper HTML option tag like

1
Text

Formatting HTML options is easy but when there are too many, it’s damn boring.
Consider a similar problem , I had a file like this CarBrands.txt. For each and every item, I had to format it so that I can input it in an HTML select.

Of course, one way was to do it manually. Again, I hate manual tasks. So I though a little and again I found a solution that worked. Again, the solution works for Linux and only Linux.

So try to get a copy of the file above and try it.

Formatting HTML Options using AWK

First, display the whole file

1
cat carBrands.txt

Now, let’s start adding a bit of HTML in it. So lets only add the option tag with the attribute value and no text

1
2
3
4
cat carBrands.txt | awk 'BEGIN{}{ print "
" $n "

";}'

This outputs something like:

1
Audi AWZ Barkas Bitter BMW Borgward

Ok, now I’m having to add the value in ascending order from value 1 to the number of items the file contains. So its simple, I just need to start with a counter of 1 and increment it each time.

1
2
3
4
cat carBrands.txt | awk 'BEGIN {val=1}{ print "
" $n "

";val++}'

So, as you may already know, the first {} of awk is run at start, the middle one is run for each line and the last is run at end. So, I here, I need only the first one for initialising the counter and middle one for each like. Finally, thats how many options looks like :)

1
Audi AWZ Barkas Bitter BMW Borgward

Formatting HTML options using AWK is useful only if you have lots of options. Lol, Don’t use this if you have only 2 options. AWK is interesting, isn’t it? I’m also thinking of learning a little bit more of it. Here are two links I’ve considered: