Friday, April 11, 2008

Awk and Eval


Suppose you have a function named
f_factory ()
which needs 2 parameters "inputfile" and "flag"

And you have a configuration file named ctrl.cfg of the following format

$ cat ctrl.cfg
#Sl No|Input File|Falg|Vol
1|/opt/ctrl.txt|tr_2|2
2|/usr/local/ms/ts.txt|tr_3|3
3|/opt/dec.txt|tr_4|2


Assignment: You have to execute(call) the function with all the "inputfile" "flag" entries from ctrl.cfg.

i.e.

f_factory "/opt/ctrl.txt" tr_2
f_factory "/usr/local/ms/ts.txt" tr_3
f_factory "/opt/dec.txt" tr_4

Solution:
---------
$ for line in `awk -F "|" '!/#/ && NF!=0 {print}' ctrl.cfg`
> do
> IFILE=`echo $line | awk -F "|" '{print $2}'`
> FLAG=`echo $line | awk -F "|" '{print $3}'`
> f_factory $IFILE $FLAG
> done

or

IFILE=`echo $line | awk -F "|" '{print $2}'`
FLAG=`echo $line | awk -F "|" '{print $3}'`

can be replaced with a single line using eval.


$ for line in `awk -F "|" '!/#/ && NF!=0 {print}' ctrl.cfg`
> do
> eval $(echo "$line" | awk -F'|' '{print "IFILE="$2";FLAG="$3}')
> f_factory "${IFILE}" "${FLAG}"
> done

No comments:

© Jadu Saikia www.UNIXCL.com