Replace using awk on fixed width file.

All,

I used to use following command to replace specific location in a fixed width file.

Recently looks like my command stopped working as intended. We are on AIX unix.

awk 'function repl(s,f,t,v)
{ return substr(s,1,f-1) sprintf("%-*s", t-f+1, v) substr(s,t+1) }
NR<=10 { a=repl($0,474,1,"Y")
  a=repl(a,476,1,"N")
  a=repl(a,478,10,"2011-01-01")
  a=repl(a,489,10,"2011-12-31")
  print a
} 
NR>10 && NR<=20 { a=repl($0,474,1,"N")
  a=repl(a,476,1,"Y")
  a=repl(a,478,10,"2015-01-01")
  a=repl(a,489,10,"2015-12-31")
  print a
}
NR>20 ' filename  > filename.new

Currently the command is replacing incorrectly and the output seems to be wierd layout than the original file.

Appreciate your help on fixing this.

Could you also post an anonymized sample of your input and the intended output...

May I question that your script has ever worked, no matter what the system was? t-f+1 with f=478 and t=1 will yield a negative number not suitable as a width parameter for sprintf . Even if you remove the - sign from the format string, the result is inacceptable, adding about 2000 spaces to each of your lines.
Try

return substr(s,1,f-1) sprintf("%-*s", t, v) substr(s,f+t) } 

and report back on the results.

It looks like your repl function was written to expect FROM and TO values so you should be calling it like this:

a=repl(a,478,487,"2011-01-01")

Or update repl() to use FROM and LENGTH as RudiC mentioned:

function repl(s,f,L,v)
{ return substr(s,1,f-1) sprintf("%-*s", L, v) substr(s,f+L) }
$ printf "%c" {1..9} {0..9} | awk '
function repl(s,f,L,v) { return substr(s,1,f-1) sprintf("%-*s", L, v) substr(s,f+L) }
{print repl($0,8,3,"AB") }'
1234567AB 123456789