Implement “wc -l” in Cisco IOS

Sometimes it would be nice to have the full complement of Unix utilities available on Cisco IOS. That's not going to happen for a while, but we can use Tcl to make our life simpler in the meantime. Xavier Brouckaert, a regular contributor to my blog, has sent me the Tcl implementation of line counting utility (equivalent to wc -l on Unix).

First you have to define the wc Tcl procedure:
proc wc { cmd } { llength [split [exec $cmd] "\n" ] }
You can define the procedure interactively in Tclsh (but then you have to do it every time you start Tclsh) or you could store the code in a flash file and execute the file every time the Tclsh is started with the scripting tcl init filename global configuration command.

Once the wc procedure is defined, execute wc { IOS command } in Tclsh and you'll get the line count. For example, to get the number of directly connected routes use
wc { show ip route ¦ include ^C }

The include ^C filter includes all lines that start with letter C; in our case all directly connected routes

Obviously you could turn this idea into a full-blown Tclsh script that would accept CLI arguments … but I'll leave this as an exercise for the readers (you can probably tell I've been reading some academic literature lately :). However, if you find the time to write a more complete wc implementation on IOS, please do post the URL here.

2 comments:

  1. wc { show ip route ¦ include ^C }
    won't work. :(
    The Tcl sheel says:
    % Invalid input detected at '^' marker.

    wc { show ip route | include ^C }
    work as expected.
    What's the difference?
  2. The "vertical bar" in the example should be the "usual" vertical bar (ASCII code 0x7C : |).

    However, Blogger has the tendency to silently "eat" this character, so I'm replacing it with the "broken vertical bar" (Unicode 0xA6), which is not recognized by the router if you do straight cut-and-paste from the text.
Add comment
Sidebar