Help with awk - variable

Hi All,

would appreciate help with the awk statement below, i not seeing the value of "color" as the variable in awk. not sure what i am missing

cat fruits
red:apples
yellow:banana
 cat fruits | awk '{
  if ( $1 == "red" ) {
                    color=red
           } else {
                    color=yellow
           }; split($0,a,":"); print "color of fruit found is", color } END { print "End of colour report"}'

output:

color of fruit found is
color of fruit found is
End of colour report!

As you don't assign FS (the field separator), the default (multiple white space) is taken. Thus $1 is always the entire line, "red" is not found, and the else branch of your if construct is taken. color is assigned yellow , a variable that is not set and thus "contains" the empty string. Which then is put out.
Why do you split $0 into array a which is never used?

Please be aware that awk doesn't need cat ; awk '...' fruits will do.

1 Like
awk '
BEGIN {
        FS=":"
        }

        { # default for all lines
                color="yellow"
        }

$1 == "red" {
        color=$1
        }

        { # all lines
        fruit=$2
        print "fruit:",fruit,"color:",color
        split($0,a,":")
        print "1:",a[1]
        }

END {
        print "End of colour report, #",NR
       }
' fruits

1 Like

thanks guys, much appreciated.