From 9caea2448e168560de306a1496574dd58c645fea Mon Sep 17 00:00:00 2001
From: Denys Vlasenko <vda.linux@googlemail.com>
Date: Tue, 16 Sep 2014 01:11:13 +0200
Subject: sed: fix a buglet in s///NUM handling

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
---
 editors/sed.c       | 5 ++++-
 testsuite/sed.tests | 4 ++++
 2 files changed, 8 insertions(+), 1 deletion(-)

diff --git a/editors/sed.c b/editors/sed.c
index e18e48ab5..e1b8352fd 100644
--- a/editors/sed.c
+++ b/editors/sed.c
@@ -395,7 +395,9 @@ static int parse_subst_cmd(sed_cmd_t *sed_cmd, const char *substr)
 	/* process the flags */
 
 	sed_cmd->which_match = 1;
+	dbg("s flags:'%s'", substr + idx + 1);
 	while (substr[++idx]) {
+		dbg("s flag:'%c'", substr[idx]);
 		/* Parse match number */
 		if (isdigit(substr[idx])) {
 			if (match[0] != '^') {
@@ -403,7 +405,7 @@ static int parse_subst_cmd(sed_cmd_t *sed_cmd, const char *substr)
 				const char *pos = substr + idx;
 /* FIXME: error check? */
 				sed_cmd->which_match = (unsigned)strtol(substr+idx, (char**) &pos, 10);
-				idx = pos - substr;
+				idx = pos - substr - 1;
 			}
 			continue;
 		}
@@ -443,6 +445,7 @@ static int parse_subst_cmd(sed_cmd_t *sed_cmd, const char *substr)
 		case '}':
 			goto out;
 		default:
+			dbg("s bad flags:'%s'", substr + idx);
 			bb_error_msg_and_die("bad option in substitution expression");
 		}
 	}
diff --git a/testsuite/sed.tests b/testsuite/sed.tests
index 9494ac2de..19f2915ce 100755
--- a/testsuite/sed.tests
+++ b/testsuite/sed.tests
@@ -329,6 +329,10 @@ line with \\
 continuation
 "
 
+testing "sed s///NUM test" \
+	"sed -e 's/a/b/2; s/a/c/g'" \
+	"cb\n" "" "aa\n"
+
 # testing "description" "commands" "result" "infile" "stdin"
 
 exit $FAILCOUNT
-- 
cgit v1.2.3-55-g6feb