1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.