msed: add s///d flag to remove on match

pull/82/head
Leah Neukirchen 6 years ago
parent 5e7c300b42
commit 07f3f044ed

@ -97,6 +97,14 @@ where
.Ar N .Ar N
is between 1 and 9. is between 1 and 9.
.Pp .Pp
If
.Ar flags
contains the letter
.Sq Cm d ,
the header is removed if
.Ar regex
matched.
.Pp
By default, only the first match is replaced, unless By default, only the first match is replaced, unless
.Ar flags .Ar flags
contains the letter contains the letter

@ -20,8 +20,9 @@ subst(char *str, char *srch, char *repl, char *flags)
static char buf[4096]; static char buf[4096];
char *bufe = buf + sizeof buf; char *bufe = buf + sizeof buf;
int iflag = !!strchr(flags, 'i'); int dflag = !!strchr(flags, 'd');
int gflag = !!strchr(flags, 'g'); int gflag = !!strchr(flags, 'g');
int iflag = !!strchr(flags, 'i');
#define APP(o, l) do { if (bufe-b < (ssize_t)l) return str; memcpy(b, str+i+o, l); b += l; } while (0) #define APP(o, l) do { if (bufe-b < (ssize_t)l) return str; memcpy(b, str+i+o, l); b += l; } while (0)
#define APPC(c) do { if (b >= bufe) return str; *b++ = c; } while (0) #define APPC(c) do { if (b >= bufe) return str; *b++ = c; } while (0)
@ -38,6 +39,9 @@ subst(char *str, char *srch, char *repl, char *flags)
if (regexec(&srchrx, str+i, 9, pmatch, 0) != 0) if (regexec(&srchrx, str+i, 9, pmatch, 0) != 0)
break; break;
if (dflag)
return 0;
APP(0, pmatch[0].rm_so); APP(0, pmatch[0].rm_so);
char *t = repl; char *t = repl;
@ -186,7 +190,7 @@ sed(char *file)
while (*e && *e != sep) while (*e && *e != sep)
e++; e++;
char *u = ++e; char *u = ++e;
while (*e == 'i' || *e == 'g') while (*e == 'd' || *e == 'g' || *e == 'i')
e++; e++;
if (!(*e == ' ' || *e == ';' || *e == '\n' || !*e)) { if (!(*e == ' ' || *e == ';' || *e == '\n' || !*e)) {
@ -200,9 +204,13 @@ sed(char *file)
char *flags = strndup(u, e-u); char *flags = strndup(u, e-u);
char *ov = v; char *ov = v;
v = strdup(subst(ov, from, to, flags)); char *r = subst(ov, from, to, flags);
free(ov); if (r)
v = strdup(r);
else
v = 0;
free(ov);
free(from); free(from);
free(to); free(to);
free(flags); free(flags);

Loading…
Cancel
Save