The UNIX and Linux Forums  

Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting
Google UNIX.COM


Shell Programming and Scripting Post questions about KSH, CSH, SH, BASH, PERL, PHP, SED, AWK and OTHER shell scripts here.

Reply
 
Submit Tools LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 03-23-2008
Registered User
 

Join Date: Aug 2007
Posts: 46
Stumble this Post!
Awk help

Hi All,

Code:
$ cat file.txt
Name    Age     Sex
A       23      M
B       21      F
C       21      M
D       21      M
I can print the 2nd field i.e "Age" field as
Code:
$ awk '{print $2}' file.txt
Age
23
21
21
21
But I want to print in a way that, instead of mentioning 2nd field, I would say "print the field with heading "Age""

I tried something like this,
Code:
$ awk '{ for(j=1;j<=NF;j++) { if ($j ~ /Age/) {print $j}}}' file.txt
But I am struggling.
Please help.

HTH,
jkl_jkl
Reply With Quote
Forum Sponsor
  #2 (permalink)  
Old 03-23-2008
Moderator
 

Join Date: Dec 2003
Location: /dev/florida
Posts: 954
Stumble this Post!
Code:
awk -v header="Age" '
BEGIN { col=0 }
NR == 1 { for (j=1;j<=NF;j++) { if ($j==header) { col=j }} }
NR > 1  { print $col }
' file.txt
Reply With Quote
Google The UNIX and Linux Forums
Reply

Thread Tools
Display Modes




All times are GMT -7. The time now is 07:49 AM.


Powered by: vBulletin, Copyright ©2000 - 2006, Jelsoft Enterprises Limited.
The UNIX and Linux Forums Content Copyright ©1993-2008 The CEP Blog All Rights Reserved -Ad Management by RedTyger Visit The Global Fact Book

Content Relevant URLs by vBSEO 3.2.0