problem in assigning substr to a variable inside awk

Hi All,

I have a fixed-width datafile from which i need to extract value/string starting from some position to the specified length in each of the lines.

awk '{print substr($0,x,y)}' datafile --- is working fine

but

awk 'BEGIN{a=0}{a=substr($0,x,y);print $a}' datafile ---is giving unexpected results:confused:

Is there any limitation in using substr() in awk?

Also why can't we use ${str:x:y} instead of substr? If yes let me know how.

This is my first post in this forum.
Thanks in advance.

Because it'shell, not awk syntax.
This should provide the same result (after replaceing x, y by their numeric equivalents (NB: index start at 0):

while read; do echo "${REPLY:x:y}"; done < datafile

$REPLY is the default content of read if no variable name is given.

Also use: print a instead of print $a inside awk..

1 Like

Now i'm able to get valid results.
Thanks for your immediate replies.:slight_smile: