If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Data Access, Manipulation & Batch Languages > Unix Shell Scripts > More Newbness

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 03-23-04, 00:18
Micster Micster is offline
Registered User
 
Join Date: Feb 2004
Posts: 5
More Newbness

I want to take a shell variable and use it in an awk command

Example:

>var="Hello People"
>awk -F":" '$2 == var {print $0}' filename

Jean thanks in advance, ha, or thanks to who ever else answers these forums.
Reply With Quote
  #2 (permalink)  
Old 03-23-04, 01:56
aigles aigles is offline
Registered User
 
Join Date: Jan 2004
Location: Bordeaux, France
Posts: 319
Two solutions :

Play with shell quotes :
Code:
var="Hello People"
awk -F":" '$2 == "'"$var"'" {print $0}' filename
Executes : awk -F":" '$2 == "Hello People" {print $0}' filename

The other solution (my prefered) is to use awk variables :
Code:
var="Hello People"
awk -F":" -v awkvar="$var" '$2 == awkvar {print $0}' filename
__________________
Jean-Pierre.
Reply With Quote
  #3 (permalink)  
Old 03-23-04, 03:31
Damian Ibbotson Damian Ibbotson is offline
Padawan
 
Join Date: Jun 2002
Location: UK
Posts: 525
Hi Micster,

Just so you don't think JP is out on a limb here, I'll chip in my 2 cents...

There are 2 ways to pass a variable to awk using awk syntax (there are many others using the shell but we'll ignore that).

The original method implemented in awk was to declare a variable after the awk command.

e.g. awk '{print var}' var="hello world"

The second method was introduced a little later in the life of awk and was implemented in order that a passed variable could be used in a BEGIN block. This uses the -v flag as illustrated by JP.

Compare the following 2 examples:

awk -v var="hello world" 'BEGIN {print var}'

awk 'BEGIN {print var}' var="hello world"

The second example will not output anything because the variable would only be available in the main body (and the END block).

I guess this is why the -v method is preferred by most (including myself).

HTH
Reply With Quote
  #4 (permalink)  
Old 03-23-04, 08:29
Micster Micster is offline
Registered User
 
Join Date: Feb 2004
Posts: 5
Man you guys are great! It might seem like small stuff to you guys but I beat my head on this for 6 hours lastnight the whole time cursing mentally at my instructor.

As always thanks so much!
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On