0

I'd like to do the equivalent of this in awk (for every line, from command line):

items = split(',')
if items[2] >= 10:
  return items[0], items[1], 7
if 4 < items[2] < 10:
  return items[0], items[1], 2
return  items[0], items[1], 1

The file is in csv format, with 3 fields.

1
  • 1
    Some of the question people can guess at, but items[:1] is obscure. Oct 17, 2016 at 9:24

2 Answers 2

2

Save the following text as, for example, xxx.awk

#!/usr/bin/awk -f
BEGIN {
   FS="," ; 
}{
   if ( $3 >= 10 ) {
      print $1" "$2" "7 ; 
   } else if ( 4 < $3 && $3 < 10 ) {
      print $1" "$2" "2 ;
   } else {
       print $1" "$2" "1 ;
   }
}

Then, run it by

./xxx.awk  yourCSVfile

Remember performing the command line: "chmod +x xxx.awk" before running.

0
  • split syntax is split(i,items,",") (split string i in array items separated by , )
  • index start at 1
  • awk do not support a < b < c construct
  • concatenation is done by a b

you simply want

split(i,items,",")
if (items[3] >= 10)
  return items[1] items[2] 7 ;
if (4 < items[3] ) ## if item[2]>=10, code isn't reached
  return items[1] items[2] 2 ;
return  items[1] items[2] 1

give (input string => result)

11,11,11 => 11117
5,5,5 => 552
1,1,1 => 111

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .