[PATCH v2 1/2] sed: implement (GNU extension) 'z' command.

Jeremy Drake busybox at jdrake.com
Thu Mar 6 16:31:57 UTC 2025


This 'z'aps (empties) the pattern space, without starting a new cycle
like 'd' does.
---
v2: remove inline comment, add tests based on tests for 'd'

 editors/sed.c       | 9 +++++++--
 testsuite/sed.tests | 5 +++++
 2 files changed, 12 insertions(+), 2 deletions(-)

diff --git a/editors/sed.c b/editors/sed.c
index 6179c5e80..2c8231448 100644
--- a/editors/sed.c
+++ b/editors/sed.c
@@ -531,7 +531,7 @@ static int parse_subst_cmd(sed_cmd_t *sed_cmd, const char *substr)
  */
 static const char *parse_cmd_args(sed_cmd_t *sed_cmd, const char *cmdstr)
 {
-	static const char cmd_letters[] ALIGN1 = "saicrw:btTydDgGhHlnNpPqx={}";
+	static const char cmd_letters[] ALIGN1 = "saicrw:btTydDgGhHlnNpPqxz={}";
 	enum {
 		IDX_s = 0,
 		IDX_a,
@@ -557,6 +557,7 @@ static const char *parse_cmd_args(sed_cmd_t *sed_cmd, const char *cmdstr)
 		IDX_P,
 		IDX_q,
 		IDX_x,
+		IDX_z,
 		IDX_equal,
 		IDX_lbrace,
 		IDX_rbrace,
@@ -639,7 +640,7 @@ static const char *parse_cmd_args(sed_cmd_t *sed_cmd, const char *cmdstr)
 	/* if it wasn't a single-letter command that takes no arguments
 	 * then it must be an invalid command.
 	 */
-	else if (idx >= IDX_nul) { /* not d,D,g,G,h,H,l,n,N,p,P,q,x,=,{,} */
+	else if (idx >= IDX_nul) {
 		bb_error_msg_and_die("unsupported command %c", sed_cmd->cmd);
 	}

@@ -1485,6 +1486,10 @@ static void process_files(void)
 			G.hold_space = tmp;
 			break;
 		}
+		case 'z': /* Zap pattern space */
+			free(pattern_space);
+			pattern_space = xzalloc(1);
+			break;
 		} /* switch */
 	} /* for each cmd */

diff --git a/testsuite/sed.tests b/testsuite/sed.tests
index 626542e33..39fd4c772 100755
--- a/testsuite/sed.tests
+++ b/testsuite/sed.tests
@@ -105,6 +105,11 @@ testing "sed d ends script iteration" \
 testing "sed d ends script iteration (2)" \
 	"sed -e '/ook/d;a\' -e 'bang'" "woot\nbang\n" "" "ook\nwoot\n"

+testing "sed z continues script iteration" \
+	"sed -e '/ook/z;s/ook/ping/p;i woot'" "woot\n\n" "" "ook\n"
+testing "sed z continues script iteration (2)" \
+	"sed -e '/ook/z;a\' -e 'bang'" "\nbang\nwoot\nbang\n" "" "ook\nwoot\n"
+
 # Multiple files, with varying newlines and NUL bytes
 test x"$SKIP_KNOWN_BUGS" = x"" && {
 testing "sed embedded NUL" "sed -e 's/woo/bang/'" "\0bang\0woo\0" "" \
-- 
2.48.1.windows.1



More information about the busybox mailing list