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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to pass an awk variable to shell scripts?

Status
Not open for further replies.

pengpeng

Programmer
Dec 18, 2002
6
US
Hi,

I need do some calculate in awk script, then pass the values out. For example,

#!/bin/bash
cat example.txt | awk -v T_C=$TC T_V=$TV '{
if( $0 ! /^ABC/ ){
T_C=T_C+1;
}
if( $0 ! /^XYZ/ ){
T_V=T_V+1;
}
}'
echo $TC
echo $TV

How could I pass the values of T_C and T_V out to my shell script?

Thanks.

 
eval `nawk -f var.awk < /dev/null`
echo ${aPOW2}

#-------------- var.awk
BEGIN {
a=2
b=4
printf(&quot;aPOW2=%d ;bPOW2=%d\n&quot;, a*a, b*b);
}


vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Typically you could use a shell function for this.
Something like..

function ret_from_awk() {
pat=$1
val=$2
fname=$3

awk -v p=$pat -v vl=$val ' {
if ($0 !~ p) {
vl++
}
} END {printf(&quot;%d\n&quot;,vl)
}' $fname
return
}
ex:
ret_from_awk t..* 1 scrap.txt
3


 
Vlad's is better.
You would also need to store the functions output in
the variable you are using for my example.

a1=`ret_from_awk t..* 1 scrap.txt`
 
It works after I used your method.

Thank you both very much.

Pengpeng
 
Hi ,
I have the same problem, and I think I did not understand from the code snippet how to get back variables from awk to shell.
My code looks like this:
read string
awk -v VAR=&quot;$string&quot; 'BEGIN {
split (VAR,arr,&quot; &quot;)
{print arr[2]}
}'

I want to get the values stored in array arr to the shell.
Can someone help.

~
 

myVar=`echo &quot;${string}&quot; | nawk '{print $2}'`

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

Part and Inventory Search

Sponsor

Back
Top