Operating System - HP-UX
1821188 Members
3388 Online
109631 Solutions
New Discussion юеВ

Re: AWK environment variables

 
SOLVED
Go to solution
u856100
Frequent Advisor

AWK environment variables

Hi people,

I am trying to figure out how to set a variable in the middle of an awk statement i.e.

#set a variable that I need
#to reference within an awk
#statement (called FIELD_ERR)
FIELD_ERR=0
for
do
while read x
do
x=$(echo $x | awk -F"|" '{
if (NF == 20) {printf }
#try and change the variable here
else if (NF > 20) {ENVIRON ["FIELD_ERR"] = "1"}
else {print $0} }')
echo $x >> ${db02file}.out
done < $db02file

# but this is where I can't reference it!
#if I print it, it is still 0 despite the
#condition above being met
if [ $FIELD_ERR -eq 1 ]
then
echo "reached"
fi
done

echo $FIELD_ERR

any help would be appreciated with regards to referencing variables declared outside an awk statement, that are then used inside it!

let me know if this is not clear!

cheers
John
chicken or egg first?
5 REPLIES 5
Jean-Louis Phelix
Honored Contributor
Solution

Re: AWK environment variables

Hi,

I think that you can't do it this way ... when you use a awk command, it forks a new process, so you will never be able to access any env var in this environment from its parent process. ENVIRON can only be used to READ variables from env.

Regards,

Jean-Louis.
It works for me (┬й Bill McNAMARA ...)
A. Clay Stephenson
Acclaimed Contributor

Re: AWK environment variables

What you are trying to do is
have a child change the environment of a parent process. That can't be done - the direction of data flow is one way - parent to child. About the only way to do something like this is to have the child process write to a file (or a named pipe) and then the parent could read the file (or pipe) and set the variable.
If it ain't broke, I can fix that.
Jean-Louis Phelix
Honored Contributor

Re: AWK environment variables

hi,

Perhaps try :

ERRFILE=/tmp/awk$$
FIELD_ERR=0
for
do
while read x
do
x=$(echo $x | awk -v errfile="$ERRFILE" -F"|" '{
if (NF == 20) {printf }
#try and change the variable here
else if (NF > 20) {system("touch " errfile) }
else {print $0} }')
echo $x >> ${db02file}.out
done < $db02file

if [ -r "$ERRFILE" ]
then
echo "reached"
fi
done


Regards,

Jean-Louis.
It works for me (┬й Bill McNAMARA ...)
Tom Danzig
Honored Contributor

Re: AWK environment variables

I don't think you can change ENV vars from awk; only read them.

You could accomplish this by doing something like:

Add: BEGIN{exitcode=0} to the awk code

Change:
else if (NF > 20) {ENVIRON ["FIELD_ERR"]="1"}

to

else if (NF > 20) {exitcode=1}


Add: END{exit exitcode} to the end of the awk script.

Then in the shell script portion right after the awk call:
export FIELD_ERR=$?

Chia-Wei
Advisor

Re: AWK environment variables

Try use awk -v to set a variable.