Home » Infrastructure » Unix » Using variable in awk
Using variable in awk [message #97629] Tue, 24 September 2002 20:10 Go to next message
Khush
Messages: 1
Registered: September 2002
Junior Member
Hi,
we use $N for the Nth parameter of the input data
string in an awk command.

How do we use a variable in the awk command? The
following is my need:

I have a file s.c like this: (delimited by 'x')
123x452x460
asdfx234xliasd
23x009xasdf

I do the following command:

cat s.c | awk -Fx '$2~/23/{print $0}'
then I get the appropriate line. (The second line
is printed)

Now, I replace the 23 with $var1. Where I have put
var1=23 before this command. But it does not work.
So I have a feeling that, there is some trick while
putting the variable into the awk command. (Because
$ has a special meaning in awk).

So how to make it parametric?

Thanks

Khushnuma
Re: Using variable in awk [message #97636 is a reply to message #97629] Mon, 30 September 2002 04:34 Go to previous messageGo to next message
Shaun
Messages: 5
Registered: July 2002
Junior Member
To get an environment variable into your awk scripts
use the ENVIRON function something like this:
cat file | awk '
BEGIN { var1 = ENVIRON[["VAR1"]] }
$2 ~ var1
{... rest of awk script ...

}'
or if you want to hard code it then:
BEGIN { var1 = "23" }

Regards,
Shaun.
Re: Using variable in awk [message #97663 is a reply to message #97629] Thu, 24 October 2002 04:14 Go to previous message
B
Messages: 327
Registered: August 1999
Senior Member
don't use cat ! .... awk open the file for U !

awk -Fx -v var=23 '$2 ~ var {print $0}' s.c
Previous Topic: Creating several password files in Unix using ORAPASSWD
Next Topic: Unixware 7 tar utility
Goto Forum:
  


Current Time: Tue Apr 16 08:20:51 CDT 2024