Linux Tips: Using awk to build a contact list.

March 21, 2007 |

Because you’re a geek, you want to maintain your very own text file full of addresses and contacts of your favorite pizzerias and individuals. Btw, you did find these contacts from LXPages.com, right? ;-)

In this mini tutorial, we’ll use the awk command and create a text file with some delimiters. Delimiters are characters or a set of characters that separate two sets of data. In this case our delimiter will be ###.

We’ve created a text file called contacts.txt, which looks like this:

$ cat contacts.txt
LXPages
1 Times Square
New York, NY 11210
Phone: (212) 555-2222
Fax: (212) 555-5555
Email: blog@lxpages.com
###
di farras pizza
Phone: (718) 555-8222
###
Nicole Smith
Phone: 555-2322
Email: nsmith@columbia.edu
Comments: friend of Howard
$

Outputing Records

We will use awk to output the records containing a match. We will use RS, which is the awk record separator, and set it to ### and enclose the pattern that we would like to match in slashes. For example, here’s how to export all the records containing the string lxpages:

$ awk 'BEGIN { RS = "###" } /lxpages/' contacts.txt
LXPages
1 Times Square
New York, NY 11210
Phone: (212) 555-2222
Fax: (212) 555-5555
Email: blog@lxpages.com
$

We can put this command in a script called addr that takes a search string as an argument. The argument in this script is represented by ‘$*’.

$ cat addr
#!/bin/bash
awk 'BEGIN { RS = "###" } /'$*'/' ~/contacts.txt

Adding records

Adding records is as easy as editing the contacts.txt file or using redirection on the command line:

$ cat >> contacts.txt

Be very careful with this cat command as you can blast your data into /dev/null if you miss a > character.

And this is the end of our mini tutorial on awk. You can see the possibilities of using this handy command in so many other ways.



Comments

1 Comment so far

  1. Hysbysfwrdd cymrux xanax cheap phentermine. on December 12, 2007 12:24 am

    Voyforums cheap xanax cheap pharmacy low price….

    Xanax cheap. Hysbysfwrdd cymrux xanax cheap phentermine. Cheap generic xanax 2mg bars. Uhi foundation forums xanax cheap phentermine. Buy cheap xanax….

Name

Email

Website

Speak your mind

  • Categories

  • Sponsors