This week’s post is about a language/tool that I’ve been wanting to learn for some time: AWK. AWK (or
awk) is a UNIX command-line tool that comes with its own interpreted language for text manipulation and analysis, and it should be useful in whipping up all kinds of script-fu. Let’s get started, shall we?
According to Wikipedia…
awk programs consist of “a series of pattern-action pairs”. In other words,
ack programs consist of chained statements of the form
When analyzing a file,
awk first breaks it up into “records” (lines), and then processes each line sequentially, evaluating each
condition is true for the current line. Additionally, the
END conditions cause their respective actions to be evaluated before or after the file is analyzed, and
pattern1, pattern2 matches every record starting with the one that matches
pattern1 up to the one that matches
It is worth noting that either the
condition or the
action can be blank, in which case
condition defaults to matching everything, and
action defaults to printing the line.
awk language has a full suite of standard functions, like arithmetic, printing, writing files (using the UNIX
> syntax), piping, functions, regexps, and much more. I won’t get into a whole lot of detail here, and instead will point interested parties to some helpful resources.
With that out of the way, it’s time for the main event.
Start the music!
This week’s program is going to be an
awk script to read a file and play Morse code based on it’s contents. Lines starting with a “–” or the word “dit” will be dits, lines starting with a “_” or the word “dah” will be dahs, and blank lines will be character breaks. Here we go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
I’ve fine-tuned the timings to sound right to my inexperienced ear, but forgive me if they are not spot-on.
You can run this program by saving it as
morse_parser.awk, saving the morse you want to play in
morse.txt, and running
awk -f morse_parser.awk morse.txt. Thanks for reading, and I’ll see you next week.