[Leaplist] How many of you use awk?
Jesse Goerz
jgoerz at cfl.rr.com
Sun Apr 22 09:02:04 EDT 2007
On Sun, 2007-04-15 at 13:34 -0400, Steve Litt wrote:
> Hi Jim,
>
> Why do you use awk instead of Perl/Python/Ruby?
>
> SteveT
>
> On Saturday 14 April 2007 21:40, Jim Hartley wrote:
> > All the time! Recently I have been using it a lot on reformatting short
> > story manuscripts - every place you want to submit to asks for files
> > formatted differently. Also EXTREMELY useful for building shell scripts
> > ... like a whole bunch of "mv foo.JPEG/JPG/jpeg foo.jpg" commands to
> > clean up file names in a directory. A quick count shows that I have 48
> > .awk files in my ~/bin directory, plus many more scattered around, plus
> > of course the one-liners I just type in as needed.
> >
> > Awk is one of the most valuable tools in my toolbox.
> >
> > Jim Hartley
> >
> > Steve Litt wrote:
> > > Hi all,
> > >
> > > How many of you use awk?
> > >
> > > SteveT
Here are some of the reasons I like it. You could argue these both
ways...
1. Opening files
pass the filename in as an argument
OR
Come up with code to open file, set up loop based on "end of line"
marker
2. Looping
Ever had a one-off error that took 10 minutes to figure out? Ever
tried to nest loops searching for content without regard for indexes and
ended up in a infinite loop?
3. No complicated regex for the basics
Change IFS (internal field separator?) anytime you want, to create all
kinds of structures.
4. No complicated references or figuring out index counters
Refering to "hunks" is as easy as $0, $1, $2, $3, NF, etc.
5. With functions, you are truly event driven
Call a function any time you see a "hunk" on the input...
if $1 == "something" {do(something)}
6. Super easy to create state machines (embedded in script)
awk -v h_tmpl="$(echo ${header_template})" \
-v f_tmpl="$(echo ${footer_template})" \
-v f_prefix="${fileprefix}" \
'BEGIN {
start_page = 0;
between_page = 1;
end_page = 2;
init = 3;
page_state = init;
page_count = 0;
...
7. It's a fantastic code generator
In no time at all you can create a _simple_ "specification language"
that you parse with awk and using functions, turn into, well, whatever
you want... I used this technique at my old job, parsing csv files that
had border values (supplied by system engineers) into test programs that
tested those values.
8. As someone stated earlier, it's always on the machine.
Steve, does this mean you're going to do an article on awk?
Jesse
More information about the Leaplist
mailing list