This is probably about 1,000,000 times slower than the perl but here's an awk version just for the challenge of it. But anyway
awk -v gzin="Foo" -v gzout="Bar" '
BEGIN {FS=gzin;
cb=(substr(gzin,1,1)~/[a-z]/)?"[a-z]$":"[A-Z]$"
ca=(substr(gzin,length(gzin)-1,1)~/[a-z]/)?"^[a-z]":"^[A-Z]"
}
{printf $1; for (f=2; f<=NF; f++) printf ("%s%s", ((($(f-1) ~ cb) || ( $(f) ~ ca ))?gzin:gzout), $f) ;
print ""}' file
And it even matches the comments
ifootest // not replace this foo
Ifootest // not replace this foo
IbarTest // << replace this bar
I bar Test // << replace this bar
I_bar_Test // << replace this bar
and with -v gzin="Foo" -v gzout="Bar"
IFootest // not replace
IFooTest // not replace
iBarTest // replace
i Bar Test //replace
I_Bar_Test // replace
Walkthrough
awk -v gzin="Foo" -v gzout="Bar" '
Load your match gzin and replacement gzout as variables
BEGIN {FS=gzin;
Split on gzin
cb=(substr(gzin,1,1)~/[a-z]/)?"[a-z]$":"[A-Z]$"
Test the case of the first character of gzin and set up a regex to match it
ca=(substr(gzin,length(gzin)-1,1)~/[a-z]/)?"^[a-z]":"^[A-Z]"
Ditto the last character
}
{printf $1; for (f=2; f<=NF; f++) printf ("%s%s", ((($(f-1) ~ cb) || ( $(f) ~ ca ))?gzin:gzout), $f) ;
Iterate over the fields testing the previous and current fields and put the appropriate value between them
print ""}' file
End each line
PS I think I hurt my brain