September 15, 2008international at 1:28 pm

about

Linux awk command

Linux awk command
Hot:sun Linux awk commandsun Linux awk commandsun dark Linux awk commandsun dark Linux awk commandsun dark Linux awk command

Have you ever had a column-oriented text file, similar to a spreadsheet, but the columns weren't in the order you wanted? For instance, suppose you
had the following information in a file named "checkbook.orig":

COST         DATE            BALANCE
10.00         040198           1000.00
20.00         040298             980.00
30.00         040298             950.00

    The information is good, but you'd prefer to have the DATE column first, followed by the COST information in the second column, and the BALANCE column third.

Using awk, you can easily rearrange the columns. The following command reads the data from the file named "checkbook.orig", and writes the data to a file named "checkbook.new":
    awk '{print $2, $1, $3}' checkbook.orig > checkbook.new

This brief awk command reads each line of the original file, and for each line it reads, it writes an output line to the "new" file. As it writes each record to the new file, it rearranges the order of the columns, so that the columns now appear in the desired order!

If you prefer a little more control of the printed output, awk also has a "printf" function that's very similar to printf in the "C" programming language. Here's the same example, with a tab character in-between each column of the output:

    awk '{printf ("%st%st%sn", $2, $1, $3) }' checkbook.orig > checkbook.new

The awk command is a powerful programming utility that takes care of things like opening files and reading each line automatically, so all you have to do is tell awk how to process each line as it goes by.

information
Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • blogmarks
  • Blogosphere News
  • co.mments
  • HelloTxt
  • Ping.fm
  • Reddit
  • RSS
  • StumbleUpon
  • Suggest to Techmeme via Twitter
  • Technorati
  • Twitter
  • Yahoo! Bookmarks
  • Add to favorites
  • BlinkList
  • Diigo
  • email
  • Identi.ca
  • LinkedIn
  • Live
  • MyShare
  • MySpace
  • PDF
  • SheToldMe
  • Slashdot
  • Socialogs
  • Tumblr

related post

CBA0E3ABEB1A7038A3FD2A47BA03BC1B Linux awk command

Technorati Tags: Linux

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One comment

  1. beauty issues

    July 11th, 2010 at 3:21 PM

    Hey, I just hopped over to your site via StumbleUpon. Not somthing I would normally read, but I liked your thoughts none the less. Thanks for making something worth reading.

Leave a reply
language
participate

Back to top

blog