1

My color.cfg file from where I am reading a file is as below.

marks,<,80,green
marks,>,80,yellow

I want to convert above color.cfg file into color.awk as below

function check()
{
if ( marks < 80 )
 return "green"
if (marks > 800)
return "yellow"
}

I have a shell script like below to convert .cfg to .awk.

LINECT=0

while read LINE
 do
 var1[$LINECT]=$(echo $LINE | cut -d ',' -f1)
 var2[$LINECT]=$(echo $LINE | cut -d ',' -f2)
 var3[$LINECT]=$(echo $LINE | cut -d ',' -f3)
 var4[$LINECT]=$(echo $LINE | cut -d ',' -f4)
 LINECT=$((LINECT+1))
 done < color.cfg

echo ${var1[@]}
echo ${var2[@]}
echo ${var3[@]}
echo ${var4[@]}

echo $LINECT

cat <<EOF > color.awk
function check()
{
if (${var1[0]} ${var2[0]} ${var3[0]} )
return "${var4[0]}"
}

EOF

My problem is how to write repetitive “if blocks” while writing a color.awk

I have written “if block once but how to write if have 2 or 3 or 4 condition ?

cat <<EOF > color.awk
function check()
{
if (${var1[0]} ${var2[0]} ${var3[0]} )
return "${var4[0]}"
}
EOF
1

It makes sense to use an awk script to create an awk function...

$ awk -f script.awk file
function check() {
        if (marks < 80) return "green"
        if (marks > 80) return "yellow"
}

Where script.awk is

BEGIN {
    FS = ","
    printf("function check() {\n")
}

{
    printf("\tif (%s %s %s) return \"%s\"\n", $1, $2, $3, $4)
}

END {
    printf("}\n")
}

This simply loops over the lines in the comma-separated file and uses the fields to output if and return statements. There will be as many of these as there are lines in the input file.

I let the BEGIN and END blocks do the function header and footer, and the BEGIN block additionally sets the input field separator to a comma.

No check for valid input is performed. This would probably go into the main block in the body of the script.

Redirect the output of the script to a file, e.g. color.awk.

Adding an extra line to the input file,

marks,==,80,red

would result in

function check() {
        if (marks < 80) return "green"
        if (marks > 80) return "yellow"
        if (marks == 80) return "red"
}

Related:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.