Computing.Net > Forums > Unix > How to print columns from file

How to print columns from file

Reply to Message Icon

Original Message
Name: WANDr
Date: March 25, 2003 at 10:49:14 Pacific
Subject: How to print columns from file
OS: Unix
CPU/Ram: AMD 512
Comment:

How do you print an entire column from a seperate file. I need to write a script entirely in korn that will prompt the user to enter the fields that they wish to display, and with that information display the correct fields. The data file looks similiar to this.


filename: inventory

color size item
red small shirt
blue large skirt
green medium hat

Say a user ask for columns 1&3 (color column and the item column). The field should print:

color item
red shirt
blue skirt
green hat



Report Offensive Message For Removal


Response Number 1
Name: Jimbo
Date: March 25, 2003 at 23:21:00 Pacific
Reply: (edit)

#! /bin/ksh
# Print columns specified by the user
FILE=/path/to/file

print "Enter the first column to print \c "
read COL1

print "Enter the second column to print \c "
read COL2

nawk "{printf \"%-10s %10s\n\", \$$COL1, \$$COL2}" $FILE


Report Offensive Follow Up For Removal

Response Number 2
Name: nails
Date: March 26, 2003 at 09:23:51 Pacific
Reply: (edit)

Hi:

Jimbo's solution is good, but if you really need to eliminate the (n)awk call, you can use the shell:

#!/bin/ksh

print "Enter the first column to print \c "
read COL1

print "Enter the second column to print \c "
read COL2

# build the echo command string
bcom="echo \$$COL1 \$$COL2"
echo $bcom
while read line
do
set - `echo $line`
eval $bcom
done data.file
# the above line a less than sign between the done and data.file

I build a string to determine which arguments to echo, 1,2, or 3. The while loop reads each line. the set command sets the arguments in the shell $1, $2, $3. Finally, I force an execution of the built command producing the results.

Regards,


Nails


Report Offensive Follow Up For Removal







Use following form to reply to current message:

   Name: From My Computing.Net Settings
 E-Mail: From My Computing.Net Settings

Subject: How to print columns from file

Comments:

 


  Homepage URL (*): 
Homepage Title (*): 
         Image URL: 
 
Data Recovery Software




Have you ever used OpenOffice?

Yes, as my main suite.
Yes, occationally.
Yes, but only once.
No, never.


View Results

Poll Finishes In 4 Days.
Discuss in The Lounge