Domanda

So basically i have a file with pipe separated lines, i would like to cut the field's content when they go over a certain length, so i have set a max length for each field. I'm using arrays in order to store the value of the max length for each field:

    gawk -F"|" -- '

BEGIN {
    map[1]=10
    map[2]=20
    map[3]=60
    map[4]=60
    map[5]=3
    map[6]=60
    map[7]=3

    OFS="|"
}

{
   for(i = 1; i <= NF; i++) {
      if (length($i) > map[$i]) {
        $i = substr($i, 1, map[$i])
      }
   }
   print;
}
'

The problem here is that there is something wrong with the array, the items all return null or 0 so that all comparisons if (length($i) > map[$i]) return true and it will empty all fields, Whats wrong with my array?

È stato utile?

Soluzione

Change (length($i) > map[$i]) to (length($i) > map[i]) and substr($i, 1, map[$i]) to substr($i, 1, map[i]) .

Like this:

    gawk -F"|" -- '

BEGIN {
    map[1]=10
    map[2]=20
    map[3]=60
    map[4]=60
    map[5]=3
    map[6]=60
    map[7]=3

    OFS="|"
}

{
   for(i = 1; i <= NF; i++) {
      if (length($i) > map[i]) {
        $i = substr($i, 1, map[i])
      }
   }
   print;
}
'

$i refers to the contents of field number i, but the contents of that field is not the index of map.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top