Bookmark and Share

How to Process a CSV File With AWK

Awk is a powerful scripting language designed exclusively for the manipulation of text files. In skillful hands, it can be a powerful tool for taking much of the monotony out of otherwise repetitive computer tasks. For example, Awk can be used to retrieve and even reformat data in the popular CSV (Comma Separated Value) spreadsheet format.

Difficulty: EasyInstructions1

Open a terminal. If you are in Unix or Linux, there is most likely a terminal icon sitting on your desktop. On Mac OS X, click the hourglass "Spotlight" icon and type "Terminal." In Windows, click "Start," "Run," and type "cmd."

2

Type the following Awk command to quickly print out all the data in the CSV file with the commas removed:awk -F ",*" '{print $1, $2, $3}' file.csvThis assumes you have a three column CSV and prints the first ($1), second ($2), and third ($3) columns in the CSV.

3

Type the following Awk command to pull data from the columns and insert them into a letter. For example, if column one holds a name, column two an address, and column three a phone number, you might type:awk -F ",*" '{print $1,", we are happy to tell you that your home at",$2,"is now ready for you to move back in. We tried to call you at the number",$3,", but you were unavailable."}' contacts.csvThis would print, for every set of name, address, and phone numbers in the contact CSV file, the following:Adam Rollins, we are happy to tell you that your home at 1013 Evergreen Terrace is now ready for you to move back in. We tried to call you at the number 817-546-6842, but you were unavailable.

References LowFatLinux: Linux Awk