2 * sed.c - very minimalist version of sed
4 * Copyright (C) 1999,2000,2001 by Lineo, inc. and Mark Whitley
5 * Copyright (C) 1999,2000,2001 by Mark Whitley <markw@codepoet.org>
6 * Copyright (C) 2002 Matt Kraai
7 * Copyright (C) 2003 by Glenn McGrath <bug1@optushome.com.au>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 Supported features and commands in this version of sed:
29 - address matching: num|/matchstr/[,num|/matchstr/|$]command
30 - commands: (p)rint, (d)elete, (s)ubstitue (with g & I flags)
31 - edit commands: (a)ppend, (i)nsert, (c)hange
32 - file commands: (r)ead
33 - backreferences in substitution expressions (\1, \2...\9)
34 - grouped commands: {cmd1;cmd2}
35 - transliteration (y/source-chars/dest-chars/)
36 - pattern space hold space storing / swapping (g, h, x)
37 - labels / branching (: label, b, t)
39 (Note: Specifying an address (range) to match is *optional*; commands
40 default to the whole pattern space if no specific address match was
46 - and lots, lots more.
50 - Cant subst globally using ^ or $ in regex, eg. "aah" | sed 's/^a/b/g'
52 Reference http://www.opengroup.org/onlinepubs/007904975/utilities/sed.html
56 #include <unistd.h> /* for getopt() */
58 #include <string.h> /* for strdup() */
60 #include <ctype.h> /* for isspace() */
64 typedef struct sed_cmd_s {
65 /* Order by alignment requirements */
68 regex_t *beg_match; /* sed -e '/match/cmd' */
69 regex_t *end_match; /* sed -e '/match/,/end_match/cmd' */
71 int beg_line; /* 'sed 1p' 0 == no begining line, apply commands to all lines */
72 int end_line; /* 'sed 1,3p' 0 == no end line, use only beginning. -1 == $ */
75 int invert; /* the '!' after the address */
76 // int block_cmd; /* This command is part of a group that has a command address */
78 /* SUBSTITUTION COMMAND SPECIFIC FIELDS */
80 /* sed -e 's/sub_match/replace/' */
84 /* EDIT COMMAND (a,i,c) SPECIFIC FIELDS */
87 /* FILE COMMAND (r) SPECIFIC FIELDS */
90 /* SUBSTITUTION COMMAND SPECIFIC FIELDS */
92 unsigned int num_backrefs:4; /* how many back references (\1..\9) */
93 /* Note: GNU/POSIX sed does not save more than nine backrefs, so
94 * we only use 4 bits to hold the number */
95 unsigned int sub_g:1; /* sed -e 's/foo/bar/g' (global) */
96 unsigned int sub_p:1; /* sed -e 's/foo/bar/p' (print substitution) */
98 /* TRANSLATE COMMAND */
103 char cmd; /* p,d,s (add more at your leisure :-) */
105 /* Branch commands */
108 /* next command in list (sequential list of specified commands) */
109 struct sed_cmd_s *next;
115 extern void xregcomp(regex_t * preg, const char *regex, int cflags);
116 extern int optind; /* in unistd.h */
117 extern char *optarg; /* ditto */
121 static int be_quiet = 0;
122 static const char bad_format_in_subst[] =
123 "bad format in substitution expression";
125 /* linked list of sed commands */
126 static sed_cmd_t sed_cmd_head;
127 static sed_cmd_t *sed_cmd_tail = &sed_cmd_head;
129 const char *const semicolon_whitespace = "; \n\r\t\v\0";
130 static regex_t *previous_regex_ptr = NULL;
133 #ifdef CONFIG_FEATURE_CLEAN_UP
134 static void destroy_cmd_strs(void)
136 sed_cmd_t *sed_cmd = sed_cmd_head.next;
139 sed_cmd_t *sed_cmd_next = sed_cmd->next;
141 if (sed_cmd->beg_match) {
142 regfree(sed_cmd->beg_match);
143 free(sed_cmd->beg_match);
145 if (sed_cmd->end_match) {
146 regfree(sed_cmd->end_match);
147 free(sed_cmd->end_match);
149 if (sed_cmd->sub_match) {
150 regfree(sed_cmd->sub_match);
151 free(sed_cmd->sub_match);
153 free(sed_cmd->replace);
155 sed_cmd = sed_cmd_next;
161 * index_of_next_unescaped_regexp_delim - walks left to right through a string
162 * beginning at a specified index and returns the index of the next regular
163 * expression delimiter (typically a forward * slash ('/')) not preceeded by
166 static int index_of_next_unescaped_regexp_delim(const char delimiter,
174 for (; (ch = str[idx]); idx++) {
176 if (ch == ']' && !(bracket == idx - 1 || (bracket == idx - 2
177 && str[idx - 1] == '^')))
185 else if (ch == delimiter)
189 /* if we make it to here, we've hit the end of the string */
193 static int parse_regex_delim(const char *cmdstr, char **match, char **replace)
195 const char *cmdstr_ptr = cmdstr;
199 /* verify that the 's' is followed by something. That something
200 * (typically a 'slash') is now our regexp delimiter... */
202 bb_error_msg_and_die(bad_format_in_subst);
204 delimiter = *cmdstr_ptr;
208 /* save the match string */
209 idx = index_of_next_unescaped_regexp_delim(delimiter, cmdstr_ptr);
211 bb_error_msg_and_die(bad_format_in_subst);
213 *match = bb_xstrndup(cmdstr_ptr, idx);
215 /* save the replacement string */
216 cmdstr_ptr += idx + 1;
217 idx = index_of_next_unescaped_regexp_delim(delimiter, cmdstr_ptr);
219 bb_error_msg_and_die(bad_format_in_subst);
221 *replace = bb_xstrndup(cmdstr_ptr, idx);
223 return ((cmdstr_ptr - cmdstr) + idx);
227 * returns the index in the string just past where the address ends.
229 static int get_address(char *my_str, int *linenum, regex_t ** regex)
233 if (isdigit(my_str[idx])) {
236 *linenum = strtol(my_str, &endstr, 10);
237 /* endstr shouldnt ever equal NULL */
238 idx = endstr - my_str;
239 } else if (my_str[idx] == '$') {
242 } else if (my_str[idx] == '/' || my_str[idx] == '\\') {
247 if (my_str[idx] == '\\') {
249 delimiter = my_str[++idx];
252 idx += index_of_next_unescaped_regexp_delim(delimiter, my_str + idx);
254 bb_error_msg_and_die("unterminated match expression");
258 *regex = (regex_t *) xmalloc(sizeof(regex_t));
259 xregcomp(*regex, my_str + idx_start, REG_NEWLINE);
260 idx++; /* so it points to the next character after the last '/' */
265 static int parse_subst_cmd(sed_cmd_t * const sed_cmd, const char *substr)
273 * the string that gets passed to this function should look like this:
274 * s/match/replace/gIp
278 * (all three of the '/' slashes are mandatory)
280 idx = parse_regex_delim(substr, &match, &sed_cmd->replace);
282 /* determine the number of back references in the match string */
283 /* Note: we compute this here rather than in the do_subst_command()
284 * function to save processor time, at the expense of a little more memory
285 * (4 bits) per sed_cmd */
287 /* sed_cmd->num_backrefs = 0; *//* XXX: not needed? --apparently not */
288 for (j = 0; match[j]; j++) {
289 /* GNU/POSIX sed does not save more than nine backrefs */
290 if (match[j] == '\\' && match[j + 1] == '('
291 && sed_cmd->num_backrefs <= 9)
292 sed_cmd->num_backrefs++;
295 /* process the flags */
296 while (substr[++idx]) {
297 switch (substr[idx]) {
301 /* Hmm, i dont see the I option mentioned in the standard */
309 /* any whitespace or semicolon trailing after a s/// is ok */
310 if (strchr(semicolon_whitespace, substr[idx]))
313 bb_error_msg_and_die("bad option in substitution expression");
318 /* compile the match string into a regex */
319 if (*match != '\0') {
320 /* If match is empty, we use last regex used at runtime */
321 sed_cmd->sub_match = (regex_t *) xmalloc(sizeof(regex_t));
322 xregcomp(sed_cmd->sub_match, match, cflags);
329 static void replace_slash_n(char *string)
332 int remaining = strlen(string);
334 for (i = 0; string[i]; i++) {
335 if ((string[i] == '\\') && (string[i + 1] == 'n')) {
337 memmove(string + i + 1, string + i + 1, remaining - 1);
344 static int parse_translate_cmd(sed_cmd_t * const sed_cmd, const char *cmdstr)
351 idx = parse_regex_delim(cmdstr, &match, &replace);
352 replace_slash_n(match);
353 replace_slash_n(replace);
354 sed_cmd->translate = xcalloc(1, (strlen(match) + 1) * 2);
355 for (i = 0; (match[i] != 0) && (replace[i] != 0); i++) {
356 sed_cmd->translate[i * 2] = match[i];
357 sed_cmd->translate[(i * 2) + 1] = replace[i];
362 static int parse_edit_cmd(sed_cmd_t * sed_cmd, const char *editstr)
367 * the string that gets passed to this function should look like this:
371 * | this backslash (immediately following the edit command) is mandatory
378 * as soon as we hit a TEXT line that has no trailing '\', we're done.
379 * this means a command like:
387 if ((*editstr != '\\') || ((editstr[1] != '\n') && (editstr[1] != '\r'))) {
388 bb_error_msg_and_die("bad format in edit expression");
391 /* store the edit line text */
392 sed_cmd->editline = xmalloc(strlen(&editstr[2]) + 2);
394 editstr[i] != '\0' && strchr("\r\n", editstr[i]) == NULL; i++, j++) {
395 if ((editstr[i] == '\\') && strchr("\n\r", editstr[i + 1]) != NULL) {
396 sed_cmd->editline[j] = '\n';
399 sed_cmd->editline[j] = editstr[i];
402 /* figure out if we need to add a newline */
403 if (sed_cmd->editline[j - 1] != '\n')
404 sed_cmd->editline[j++] = '\n';
406 /* terminate string */
407 sed_cmd->editline[j] = '\0';
413 static int parse_file_cmd(sed_cmd_t * sed_cmd, const char *filecmdstr)
419 * the string that gets passed to this function should look like this:
424 * optional whitespace
426 * re: the file to be read, the GNU manual says the following: "Note that
427 * if filename cannot be read, it is treated as if it were an empty file,
428 * without any error indication." Thus, all of the following commands are
431 * sed -e '1r noexist'
436 /* the file command may be followed by whitespace; move past it. */
437 while (isspace(filecmdstr[++idx])) {;
440 /* the first non-whitespace we get is a filename. the filename ends when we
441 * hit a normal sed command terminator or end of string */
442 filenamelen = strcspn(&filecmdstr[idx], semicolon_whitespace);
443 sed_cmd->filename = xmalloc(filenamelen + 1);
444 safe_strncpy(sed_cmd->filename, &filecmdstr[idx], filenamelen + 1);
445 return idx + filenamelen;
449 * Process the commands arguments
451 static char *parse_cmd_str(sed_cmd_t * sed_cmd, char *cmdstr)
453 /* handle (s)ubstitution command */
454 if (sed_cmd->cmd == 's') {
455 cmdstr += parse_subst_cmd(sed_cmd, cmdstr);
457 /* handle edit cmds: (a)ppend, (i)nsert, and (c)hange */
458 else if (strchr("aic", sed_cmd->cmd)) {
459 if ((sed_cmd->end_line || sed_cmd->end_match) && sed_cmd->cmd != 'c')
461 ("only a beginning address can be specified for edit commands");
462 cmdstr += parse_edit_cmd(sed_cmd, cmdstr);
464 /* handle file cmds: (r)ead */
465 else if (sed_cmd->cmd == 'r') {
466 if (sed_cmd->end_line || sed_cmd->end_match)
467 bb_error_msg_and_die("Command only uses one address");
468 cmdstr += parse_file_cmd(sed_cmd, cmdstr);
470 /* handle branch commands */
471 else if (strchr(":bt", sed_cmd->cmd)) {
474 cmdstr += strspn(cmdstr, " ");
475 length = strcspn(cmdstr, "; \n");
476 sed_cmd->label = strndup(cmdstr, length);
479 /* translation command */
480 else if (sed_cmd->cmd == 'y') {
481 cmdstr += parse_translate_cmd(sed_cmd, cmdstr);
483 /* if it wasnt a single-letter command that takes no arguments
484 * then it must be an invalid command.
486 else if (strchr("dgGhHnNpPqx={}", sed_cmd->cmd) == 0) {
487 bb_error_msg_and_die("Unsupported command %c", sed_cmd->cmd);
490 /* give back whatever's left over */
494 static char *add_cmd(sed_cmd_t * sed_cmd, char *cmdstr)
496 /* Skip over leading whitespace and semicolons */
497 cmdstr += strspn(cmdstr, semicolon_whitespace);
499 /* if we ate the whole thing, that means there was just trailing
500 * whitespace or a final / no-op semicolon. either way, get out */
501 if (*cmdstr == '\0') {
505 /* if this is a comment, jump past it and keep going */
506 if (*cmdstr == '#') {
507 /* "#n" is the same as using -n on the command line */
508 if (cmdstr[1] == 'n') {
511 return (strpbrk(cmdstr, "\n\r"));
515 * format is: [addr][,addr]cmd
520 /* first part (if present) is an address: either a '$', a number or a /regex/ */
521 cmdstr += get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
523 /* second part (if present) will begin with a comma */
524 if (*cmdstr == ',') {
528 idx = get_address(cmdstr, &sed_cmd->end_line, &sed_cmd->end_match);
530 bb_error_msg_and_die("get_address: no address found in string\n"
531 "\t(you probably didn't check the string you passed me)");
536 /* skip whitespace before the command */
537 while (isspace(*cmdstr)) {
541 /* there my be the inversion flag between part2 and part3 */
542 if (*cmdstr == '!') {
546 #ifdef SED_FEATURE_STRICT_CHECKING
547 /* According to the spec
548 * It is unspecified whether <blank>s can follow a '!' character,
549 * and conforming applications shall not follow a '!' character
552 if (isblank(cmdstr[idx]) {
553 bb_error_msg_and_die("blank follows '!'");}
555 /* skip whitespace before the command */
556 while (isspace(*cmdstr)) {
562 /* last part (mandatory) will be a command */
564 bb_error_msg_and_die("missing command");
566 sed_cmd->cmd = *cmdstr;
569 cmdstr = parse_cmd_str(sed_cmd, cmdstr);
571 /* Add the command to the command array */
572 sed_cmd_tail->next = sed_cmd;
573 sed_cmd_tail = sed_cmd_tail->next;
578 static void add_cmd_str(char *cmdstr)
580 #ifdef CONFIG_FEATURE_SED_EMBEDED_NEWLINE
581 char *cmdstr_ptr = cmdstr;
583 /* HACK: convert "\n" to match tranlated '\n' string */
584 while ((cmdstr_ptr = strstr(cmdstr_ptr, "\\n")) != NULL) {
585 cmdstr = xrealloc(cmdstr, strlen(cmdstr) + 2);
586 cmdstr_ptr = strstr(cmdstr, "\\n");
587 memmove(cmdstr_ptr + 1, cmdstr_ptr, strlen(cmdstr_ptr) + 1);
588 cmdstr_ptr[0] = '\\';
595 sed_cmd = xcalloc(1, sizeof(sed_cmd_t));
596 cmdstr = add_cmd(sed_cmd, cmdstr);
597 } while (cmdstr && strlen(cmdstr));
601 static void load_cmd_file(char *filename)
608 cmdfile = bb_xfopen(filename, "r");
610 while ((line = bb_get_line_from_file(cmdfile)) != NULL) {
611 /* if a line ends with '\' it needs the next line appended to it */
612 while (((e = last_char_is(line, '\n')) != NULL)
613 && (e > line) && (e[-1] == '\\')
614 && ((nextline = bb_get_line_from_file(cmdfile)) != NULL)) {
615 line = xrealloc(line, (e - line) + 1 + strlen(nextline) + 1);
616 strcat(line, nextline);
619 /* eat trailing newline (if any) --if I don't do this, edit commands
620 * (aic) will print an extra newline */
633 #define PIPE_MAGIC 0x7f
636 void pipe_putc(struct pipeline *const pipeline, char c)
638 if (pipeline->buf[pipeline->idx] == PIPE_MAGIC) {
639 pipeline->buf = xrealloc(pipeline->buf, pipeline->len + PIPE_GROW);
640 memset(pipeline->buf + pipeline->len, 0, PIPE_GROW);
641 pipeline->len += PIPE_GROW;
642 pipeline->buf[pipeline->len - 1] = PIPE_MAGIC;
644 pipeline->buf[pipeline->idx++] = (c);
647 #define pipeputc(c) pipe_putc(pipeline, c)
651 if (pipeline[pipeline_idx] == PIPE_MAGIC) {
652 pipeline = xrealloc(pipeline, pipeline_len + PIPE_GROW);
653 memset(pipeline + pipeline_len, 0, PIPE_GROW);
654 pipeline_len += PIPE_GROW;
655 pipeline[pipeline_len - 1] = PIPE_MAGIC;
657 pipeline[pipeline_idx++] = (c);
661 static void print_subst_w_backrefs(const char *line, const char *replace,
662 regmatch_t * regmatch, struct pipeline *const pipeline, int matches)
666 /* go through the replacement string */
667 for (i = 0; replace[i]; i++) {
668 /* if we find a backreference (\1, \2, etc.) print the backref'ed * text */
669 if (replace[i] == '\\' && isdigit(replace[i + 1])) {
674 ++i; /* i now indexes the backref number, instead of the leading slash */
675 tmpstr[0] = replace[i];
677 backref = atoi(tmpstr);
678 /* print out the text held in regmatch[backref] */
679 if (backref <= matches && regmatch[backref].rm_so != -1)
680 for (j = regmatch[backref].rm_so; j < regmatch[backref].rm_eo;
685 /* if we find a backslash escaped character, print the character */
686 else if (replace[i] == '\\') {
688 pipeputc(replace[i]);
691 /* if we find an unescaped '&' print out the whole matched text.
692 * fortunately, regmatch[0] contains the indicies to the whole matched
693 * expression (kinda seems like it was designed for just such a
695 else if (replace[i] == '&') {
698 for (j = regmatch[0].rm_so; j < regmatch[0].rm_eo; j++)
701 /* nothing special, just print this char of the replacement string to stdout */
703 pipeputc(replace[i]);
707 static int do_subst_command(sed_cmd_t * sed_cmd, char **line)
709 char *hackline = *line;
710 struct pipeline thepipe = { NULL, 0, 0 };
711 struct pipeline *const pipeline = &thepipe;
714 regmatch_t *regmatch = NULL;
715 regex_t *current_regex;
717 if (sed_cmd->sub_match == NULL) {
718 current_regex = previous_regex_ptr;
720 previous_regex_ptr = current_regex = sed_cmd->sub_match;
722 result = regexec(current_regex, hackline, 0, NULL, 0);
724 /* we only proceed if the substitution 'search' expression matches */
725 if (result == REG_NOMATCH) {
729 /* whaddaya know, it matched. get the number of back references */
730 regmatch = xmalloc(sizeof(regmatch_t) * (sed_cmd->num_backrefs + 1));
732 /* allocate more PIPE_GROW bytes
733 if replaced string is larger than original */
734 thepipe.len = strlen(hackline) + PIPE_GROW;
735 thepipe.buf = xcalloc(1, thepipe.len);
737 thepipe.buf[thepipe.len - 1] = PIPE_MAGIC;
739 /* and now, as long as we've got a line to try matching and if we can match
740 * the search string, we make substitutions */
741 while ((*hackline || !altered)
742 && (regexec(current_regex, hackline, sed_cmd->num_backrefs + 1,
743 regmatch, 0) != REG_NOMATCH)) {
746 /* print everything before the match */
747 for (i = 0; i < regmatch[0].rm_so; i++)
748 pipeputc(hackline[i]);
750 /* then print the substitution string */
751 print_subst_w_backrefs(hackline, sed_cmd->replace, regmatch, pipeline,
752 sed_cmd->num_backrefs);
754 /* advance past the match */
755 hackline += regmatch[0].rm_eo;
756 /* flag that something has changed */
759 /* if we're not doing this globally, get out now */
760 if (!sed_cmd->sub_g) {
764 for (; *hackline; hackline++)
766 if (thepipe.buf[thepipe.idx] == PIPE_MAGIC)
767 thepipe.buf[thepipe.idx] = 0;
777 static sed_cmd_t *branch_to(const char *label)
781 for (sed_cmd = sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
782 if ((sed_cmd->label) && (strcmp(sed_cmd->label, label) == 0)) {
787 /* If no match returns last command */
791 static void process_file(FILE * file)
793 char *pattern_space; /* Posix requires it be able to hold at least 8192 bytes */
794 char *hold_space = NULL; /* Posix requires it be able to hold at least 8192 bytes */
795 static int linenum = 0; /* GNU sed does not restart counting lines at EOF */
796 unsigned int still_in_range = 0;
800 pattern_space = bb_get_chomped_line_from_file(file);
801 if (pattern_space == NULL) {
805 /* go through every line in the file */
810 /* This enables whole blocks of commands to be mask'ed out if the lead address doesnt match */
813 /* Read one line in advance so we can act on the last line, the '$' address */
814 next_line = bb_get_chomped_line_from_file(file);
820 /* for every line, go through all the commands */
821 for (sed_cmd = sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
825 * entry point into sedding...
828 /* no range necessary */
829 (sed_cmd->beg_line == 0 && sed_cmd->end_line == 0
830 && sed_cmd->beg_match == NULL
831 && sed_cmd->end_match == NULL) ||
832 /* this line number is the first address we're looking for */
833 (sed_cmd->beg_line > 0 && (sed_cmd->beg_line == linenum)) ||
834 /* this line matches our first address regex */
836 && (regexec(sed_cmd->beg_match, pattern_space, 0, NULL,
838 /* we are currently within the beginning & ending address range */
839 still_in_range || ((sed_cmd->beg_line == -1)
840 && (next_line == NULL))
842 if (sed_cmd->cmd == '{') {
843 block_mask = block_mask & matched;
845 // matched &= block_mask;
847 if (sed_cmd->invert ^ (matched & block_mask)) {
848 /* Update last used regex incase a blank substitute BRE is found */
849 if (sed_cmd->beg_match) {
850 previous_regex_ptr = sed_cmd->beg_match;
856 switch (sed_cmd->cmd) {
858 printf("%d\n", linenum);
861 /* Write the current pattern space upto the first newline */
862 char *tmp = strchr(pattern_space, '\n');
868 case 'p': /* Write the current pattern space to output */
879 * Some special cases for 's' printing to make it compliant with
880 * GNU sed printing behavior (aka "The -n | s///p Matrix"):
882 * -n ONLY = never print anything regardless of any successful
885 * s///p ONLY = always print successful substitutions, even if
886 * the pattern_space is going to be printed anyway (pattern_space
887 * will be printed twice).
889 * -n AND s///p = print ONLY a successful substitution ONE TIME;
890 * no other lines are printed - this is the reason why the 'p'
891 * flag exists in the first place.
894 #ifdef CONFIG_FEATURE_SED_EMBEDED_NEWLINE
895 /* HACK: escape newlines twice so regex can match them */
899 while (strchr(pattern_space + offset, '\n') != NULL) {
903 xrealloc(pattern_space,
904 strlen(pattern_space) + 2);
905 tmp = strchr(pattern_space + offset, '\n');
906 memmove(tmp + 1, tmp, strlen(tmp) + 1);
909 offset = tmp - pattern_space + 2;
913 /* we print the pattern_space once, unless we were told to be quiet */
914 substituted = do_subst_command(sed_cmd, &pattern_space);
916 #ifdef CONFIG_FEATURE_SED_EMBEDED_NEWLINE
917 /* undo HACK: escape newlines twice so regex can match them */
919 char *tmp = pattern_space;
921 while ((tmp = strstr(tmp, "\\n")) != NULL) {
922 memmove(tmp, tmp + 1, strlen(tmp + 1) + 1);
927 altered = substituted;
928 if (!be_quiet && altered && ((sed_cmd->next == NULL)
929 || (sed_cmd->next->cmd != 's'))) {
933 /* we also print the line if we were given the 'p' flag
934 * (this is quite possibly the second printing) */
935 if ((sed_cmd->sub_p) && altered) {
941 fputs(sed_cmd->editline, stdout);
946 fputs(sed_cmd->editline, stdout);
950 /* single-address case */
951 if ((sed_cmd->end_match == NULL && sed_cmd->end_line == 0)
952 /* multi-address case */
953 /* - matching text */
954 || (sed_cmd->end_match
955 && (regexec(sed_cmd->end_match, pattern_space, 0,
957 /* - matching line numbers */
958 || (sed_cmd->end_line > 0
959 && sed_cmd->end_line == linenum)) {
960 fputs(sed_cmd->editline, stdout);
969 outfile = fopen(sed_cmd->filename, "r");
974 bb_get_chomped_line_from_file(outfile)) !=
977 xrealloc(pattern_space,
978 strlen(line) + strlen(pattern_space) + 2);
979 strcat(pattern_space, "\n");
980 strcat(pattern_space, line);
982 bb_xprint_and_close_file(outfile);
987 case 'q': /* Branch to end of script and quit */
989 /* Exit the outer while loop */
993 case 'n': /* Read next line from input */
995 pattern_space = next_line;
996 next_line = bb_get_chomped_line_from_file(file);
999 case 'N': /* Append the next line to the current line */
1002 realloc(pattern_space,
1003 strlen(pattern_space) + strlen(next_line) + 2);
1004 strcat(pattern_space, "\n");
1005 strcat(pattern_space, next_line);
1006 next_line = bb_get_chomped_line_from_file(file);
1011 sed_cmd = branch_to(sed_cmd->label);
1015 sed_cmd = branch_to(sed_cmd->label);
1021 for (i = 0; pattern_space[i] != 0; i++) {
1024 for (j = 0; sed_cmd->translate[j]; j += 2) {
1025 if (pattern_space[i] == sed_cmd->translate[j]) {
1026 pattern_space[i] = sed_cmd->translate[j + 1];
1032 case 'g': /* Replace pattern space with hold space */
1033 free(pattern_space);
1034 pattern_space = strdup(hold_space);
1036 case 'G': { /* Append newline and hold space to pattern space */
1037 int pattern_space_size = 0;
1038 if (pattern_space) {
1039 pattern_space_size = strlen(pattern_space);
1041 pattern_space = xrealloc(pattern_space, pattern_space_size + strlen(hold_space) + 2);
1042 strcat(pattern_space, "\n");
1043 strcat(pattern_space, hold_space);
1046 case 'h': /* Replace hold space with pattern space */
1048 hold_space = strdup(pattern_space);
1050 case 'H': { /* Append newline and pattern space to hold space */
1051 int hold_space_size = 0;
1053 hold_space_size = strlen(hold_space);
1055 hold_space = xrealloc(hold_space, hold_space_size + strlen(pattern_space) + 2);
1056 strcat(hold_space, "\n");
1057 strcat(hold_space, pattern_space);
1061 /* Swap hold and pattern space */
1062 char *tmp = pattern_space;
1063 pattern_space = hold_space;
1071 * exit point from sedding...
1075 /* this is a single-address command or... */
1076 (sed_cmd->end_line == 0 && sed_cmd->end_match == NULL)
1077 /* If only one address */
1078 /* we were in the middle of our address range (this
1079 * isn't the first time through) and.. */
1080 || ((still_in_range == 1)
1081 /* this line number is the last address we're looking for or... */
1082 && ((sed_cmd->end_line > 0
1083 && (sed_cmd->end_line == linenum))
1084 /* this line matches our last address regex */
1085 || (sed_cmd->end_match
1086 && (regexec(sed_cmd->end_match, pattern_space,
1087 0, NULL, 0) == 0))))) {
1088 /* we're out of our address range */
1091 /* didn't hit the exit? then we're still in the middle of an address range */
1096 if (sed_cmd->cmd == '}') {
1104 /* we will print the line unless we were told to be quiet or if the
1105 * line was altered (via a 'd'elete or 's'ubstitution), in which case
1106 * the altered line was already printed */
1107 if ((!be_quiet && !altered) || force_print) {
1108 puts(pattern_space);
1110 free(pattern_space);
1111 pattern_space = next_line;
1112 } while (pattern_space);
1115 extern int sed_main(int argc, char **argv)
1117 int opt, status = EXIT_SUCCESS;
1119 #ifdef CONFIG_FEATURE_CLEAN_UP
1120 /* destroy command strings on exit */
1121 if (atexit(destroy_cmd_strs) == -1)
1122 bb_perror_msg_and_die("atexit");
1125 /* do normal option parsing */
1126 while ((opt = getopt(argc, argv, "ne:f:")) > 0) {
1132 char *str_cmd = strdup(optarg);
1134 add_cmd_str(str_cmd);
1139 load_cmd_file(optarg);
1146 /* if we didn't get a pattern from a -e and no command file was specified,
1147 * argv[optind] should be the pattern. no pattern, no worky */
1148 if (sed_cmd_head.next == NULL) {
1149 if (argv[optind] == NULL)
1152 char *str_cmd = strdup(argv[optind]);
1154 add_cmd_str(strdup(str_cmd));
1160 /* argv[(optind)..(argc-1)] should be names of file to process. If no
1161 * files were specified or '-' was specified, take input from stdin.
1162 * Otherwise, we process all the files specified. */
1163 if (argv[optind] == NULL || (strcmp(argv[optind], "-") == 0)) {
1164 process_file(stdin);
1169 for (i = optind; i < argc; i++) {
1170 file = bb_wfopen(argv[i], "r");
1175 status = EXIT_FAILURE;