How to parse a numeric string without any delimiters?

Hi ,

I have a number say 12345001 which needs to be parsed. Its a number that has no delimiters.I have to read the last three digits and then the rest of digits irrespective of the total length of the number. The digits then have to be swapped and changed to a fixed length. The fillers to be inserted are X.

In short the input is 12345001 and the output needed is 001XX12345. The total length has to be 10.

Please suggest a solution which is performance oriented because the input has to be read from a file that would have around 50K records in it.

TIA.

awk '{
  f = sprintf("%*-s", l - length + 3, substr($0, length - 2)) 
  gsub(/ /, c, f)
  print  f substr($0, 1, length - 3)
  }' l=10 c=X infile

Unfortunately i can not use gsub as its not supported. The command returned

for input

:frowning:

Please suggest an alternative.

Are you on Solaris? Use nawk .

The problem is with gsub which is not installed . I am using AIX. Thanks.

gsub is part of awk. Exactly what error are you getting when you run radoulov's script?

There is no error. The script works just fine but the output expected is not returned. Can you explain the logic pls.

radoulov's solution uses the gsub awk command, you say you can't use it - so what script are you using?

Yippeee it worked...used gawk :). Thanks.

Correction, for strings <4 or >10 chars:

awk '
function min(a,b) { if (a < b) return a; return b }
{
  f = sprintf("%*-s", min(l,l - length + 3), substr($0, length - 2)) 
  gsub(/ /, c, f)
  print  f substr($0, 1, min(l - 3, length - 3))
}' l=10 c=X infile
1 Like

Good point, I should have asked the OP to clarify how these case should be handled.