Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting
Search Forums:



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

Reply    
 
Thread Tools Search this Thread Display Modes
    #1  
Old 02-07-2012
Registered User
 

Join Date: Jul 2010
Posts: 28
Thanks: 8
Thanked 0 Times in 0 Posts
awk print using a variable

hey,

just want to ask how to do this.

ex.

Code:
g="hi i am john"
h=`echo $g | awk '{print $2}'`
echo $h

OUTPUT is 'i'

What if I want to use a variable instead of using '2', how do I do that?
Because this one does not work:

Code:
a=2
h=`echo $g | awk '{print ${$a}}'`

this one also does not work:

Code:
a=2
h=`echo $g | awk '{print $a}'`

anyone? thanks!

Last edited by Franklin52; 02-08-2012 at 05:19 AM.. Reason: Please use code tags for code and data samples, thank you
Sponsored Links
    #2  
Old 02-07-2012
balajesuri's Avatar
#! /bin/bash
 

Join Date: Apr 2009
Location: India
Posts: 1,019
Thanks: 9
Thanked 285 Times in 277 Posts

Code:
a=2
g="hi i am john"
h=`echo $g | awk -v i=$a '{print $i}'`

The Following User Says Thank You to balajesuri For This Useful Post:
h0ujun (02-08-2012)
Sponsored Links
    #3  
Old 02-08-2012
Registered User
 

Join Date: Jul 2010
Posts: 28
Thanks: 8
Thanked 0 Times in 0 Posts
Quote:
Originally Posted by balajesuri View Post
Code:
a=2
g="hi i am john"
h=`echo $g | awk -v i=$a '{print $i}'`

cool..thanks!
    #4  
Old 02-08-2012
Scrutinizer's Avatar
mother ate her
 

Join Date: Nov 2008
Location: Amsterdam
Posts: 5,371
Thanks: 80
Thanked 1,107 Times in 1,011 Posts
In shell that supports arrays (bash/ksh):

Code:
g="hi i am john"
i=2
h=( $g )
echo "${h[ $((i-1)) ]}"

Sponsored Links
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

More UNIX and Linux Forum Topics You Might Find Helpful
Thread Thread Starter Forum Replies Last Post
awk print variable zorrox Shell Programming and Scripting 7 05-07-2011 11:25 PM
How to print variable value using file. bhavesh.sapra Shell Programming and Scripting 6 10-30-2009 04:24 AM
How to print a value in the variable using awk ? jisha Shell Programming and Scripting 1 01-14-2008 06:45 AM
print the name of variable sun-guy Shell Programming and Scripting 1 08-06-2006 05:03 PM
print variable in awk kazanoova2 Shell Programming and Scripting 8 05-17-2004 06:30 PM



All times are GMT -4. The time now is 04:41 AM.