My recent encounter with the problem of different results in the CLI and in Cacti was with a shell script with some sed, awk and cut to manipulate the output of an SNMPwalk. Since you're also doing some text manipulation I'll share my experience.
I found the cuplrit by redirecting the output of every step of manipulation to a different /tmp/file. I had already done this many times in the CLI, but I only spotted a difference when I let Cacti run the script with the redirections. In a certain step the output in the CLI read TER01, while the output of the same step run by Cacti read "TER01". I couldn't see the quotes in the CLI, probably because of a terminal setting or whatnot.
Anyway, from the moment I inserted
in my manipulation, the output between CLI and Cacti were the same. So it wasn't the shebang line, it wasn't the login shell for the cacti user (www-data for me), it wasn't shell/subshell miscommunication of variables, it wasn't chmod/chown/chgrp on my script, and it wasn't a multitude of other ideas I had in the three weeks it took me to solve this.