- /* then print the substitution string */
- do_subst_w_backrefs(line, sed_cmd->string);
+ /* Then print the substitution string,
+ * unless we just matched empty string after non-empty one.
+ * Example: string "cccd", pattern "c*", repl "R":
+ * result is "RdR", not "RRdR": first match "ccc",
+ * second is "" before "d", third is "" after "d".
+ * Second match is NOT replaced!
+ */
+ if (prev_match_empty || i != 0) {
+ dbg("inserting replacement at %d in '%s'", i, line);
+ do_subst_w_backrefs(line, sed_cmd->string);
+ } else {
+ dbg("NOT inserting replacement at %d in '%s'", i, line);
+ }
+
+ /* If matched string is empty (f.e. "c*" pattern),
+ * copy verbatim one char after it before attempting more matches
+ */
+ prev_match_empty = (G.regmatch[0].rm_eo == i);
+ if (prev_match_empty && line[i]) {
+ pipe_putc(line[i]);
+ G.regmatch[0].rm_eo++;
+ }