Tim\'s picture      Blogging Ottinger (tim)

2005-October-28

awk - simple and powerful.

Filed under: Linux, Programming

I was joking with friends today about stupid one-liners in Linux. The dumbest being the one I’m most guilty of: cat $file | more. This is silly, of course, because one can easily use: less $file instead. I picked on a friend for doing cat $file | grep somepattern, and several of us admitted to using less-than-brilliant pipelining from time to time. I have even found unnecessary pipeline silliness in scripts or tutorials by respected administrators. I guess we all deserve a little forgiveness sometimes.

Awk is a very nice little tool for one-liners. I have to admit that I generally use it as a substitute for grep + cut, and that’s okay. Awk doesn’t mind. :-) I can’t tell you how many times I sucked information out of a file using a command like awk '/pattern/ {print $2}' $filename. I used to use it for much heavier tasks, but now I find that Python is better suited to the heavy lifting. Awk does my light jobs.

Here’s a common pattern (a clue that I need to write a nice shell script) when I don’t have as much CPU accessible as I think I should. I first use ps -fu tottinge | less to get a list of my processes. When I see something that I know should not be running (usually a konqueror thread or a flash viewer or sometimes a media program that didn’t fully exit) then i try ps -fu tottinge | awk '/procname/' to get the list of just the ones I care about. If I’ve got that right, then I add code to extract the process id and kill the process: ps -fu tottinge | awk '/procname/{print $2}' | xargs kill.

If there is just one or two processes, I can get it done more quickly with top and my mouse buffer.

To become skilled in awk doesn’t take much time, just a good tutorial to get you started and then a few one-line programs to use as examples. Once you get used to it, you’ll find a million uses. Well, that is, if you are writing shell scripts. :-) You can become effective very quickly.

Comments »

The URI to TrackBack this entry is: http://tottinge.blogsome.com/2005/10/28/awk-simple-and-powerful/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Anti-spam measure: please retype the above text into the box provided.

Get free blog up and running in minutes with Blogsome | Theme designs available here