Unix Tip: Printing in columns

By , ITworld.com |  Operating Systems

Send your Unix questions today!


See additional Unix tips and tricks


Regardless of how sophisticated Unix has become, one of its ever-endearing qualities is the ease with which the command line can be used to select, manipulate and display data. Clever little languages like sed and awk continue to remind me why it was so much fun to sit down with the early O'Reilly books, trying each new little "trick" that they taught me and discovering just how much processing I could do via simple scripts. And, while I rarely write awk scripts these days, there are occasions in which it is the perfect tool for the task. In this week's column, we're going to look at a couple tools for creating columnar output from a list of strings -- a simple task, but one that I hate to do "by hand".

In the first of two scripts, data arriving in a list such as this:

apricot

banana

chick peas

dill pickle

egg

french fries

grapes

hot dogs

ice cream

jello

ketchup

lemon

melon




would be processed to look like this:

apricot banana chick peas
dill pickle eggs french fries
grapes hot dogs ice cream
jello ketchup lemon
melon    




This rearrangement of data can be helpful if, for example, you are including a list of file names or numbers in a text file and want to include multiple items in each row to shorten the length of the inserted text.

For anyone who hasn't written awk scripts. it's useful to know that awk processes one line of input at a time and that it automatically assigns each string on a line to the variables $1, $2 and so on ($0 represents the entire line of input).

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Answers - Powered by ITworld

ITworld Answers helps you solve problems and share expertise. Ask a question or take a crack at answering the new questions below.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Ask a Question
randomness