awk insert character in the middle of a line

I'm trying to insert a single character at position 11 in everyline of a file.
My input file looks like this:

     456781 ~Y~12345
     456782 ~N~12300

and I want my output to look like this:

     45678~1 ~Y~12345
     45678~2 ~N~12300

I tried the following awk code, but it's not working:

cat myfile | awk 'print substr($1,1,10) "~" substr($1,11)}' > mynewfile

Any help would be appreciated!

That change doesnt look like its at position 11. It looks like position 5.

I couldnt resist a sed solution for that

sh-2.05b$ echo "456781 ~Y~12345" | sed -e 's#\(.\{5\}\)\(.*\)#\1~\2#g'
45678~1 ~Y~12345

vino

1 Like

I think you just missed the opening brace before the 'print' statement - other than that it seems to work fine.

Thanks vino and grasper! It is in position 11, the first 5 characters are spaces so it looks like it's in position 5.
The sed solutions looks a lot more complicated to me. I figured I had to use $0 instead of $1, and yes I was missing the open brace.
Thanks guys!

Monica

1 Like