Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

print out columns

Status
Not open for further replies.

krava

Programmer
Jun 4, 2007
48
0
0
YU
hi,

I would like to write out certain columns (number is not fixed) from datafile. My program starts like:


echo "chose columns separated by commas";
read col;
awk -v c=$col 'BEGIN{
search=",";
n=split(c,a,search);
for (i=1;i<=n;i++) {
print a;
}}{......}' dataFile.dat > newDataFile.dat


If for exapmple col="3,6,9" then just these 3 columns of dataFile.dat are ptinted out into newDataFile.dat; If col="2,4,7,3,66,7" then these 6 columns are printed out.

How to print out variable number of columns in awk?


k.
 
#!/bin/ksh
Try the following (a modified verion of your script)

Code:
read col?'Choose columns separated by commas: '
awk -v c="$col" -f awkfile datafile.dat

where awkfile contains

Code:
BEGIN {
     nCol = split(c, aCol, ",")
}

{
  for (i=1; i <=nCol; i++)
    printf("%s%s", $aCol[i], (i==nCol) ? ORS : OFS)
}
 
thanks for reply...works fine
 
fpmurphy said:
BEGIN {
nCol = split(c, aCol, ",")
}

{
for (i=1; i <=nCol; i++)
printf("%s%s", $aCol, (i==nCol) ? ORS : OFS)
}

Hmmm..... This reminds me of a solution at the other forum.

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top