another approach, build up a regexp and use that: fn changefield { n = $1 repl = $2 s=')([^ ]+)(.*)' for(i in `{seq 1 `{echo $n 1 -p | dc}}){ s='[^ ]+[ ]+'^$s } s='('^$s sed 's/'^$s^'/\1'^$repl^'\3/' }
(N.B. if the replacement string might contain / or \, those characters would need quoting)