1 /* vi: set sw=4 ts=4: */
3 * sed.c - very minimalist version of sed
5 * Copyright (C) 1999,2000,2001 by Lineo, inc. and Mark Whitley
6 * Copyright (C) 1999,2000,2001 by Mark Whitley <markw@codepoet.org>
7 * Copyright (C) 2002 Matt Kraai
8 * Copyright (C) 2003 by Glenn McGrath <bug1@iinet.net.au>
9 * Copyright (C) 2003,2004 by Rob Landley <rob@landley.net>
11 * MAINTAINER: Rob Landley <rob@landley.net>
13 * Licensed under GPL version 2, see file LICENSE in this tarball for details.
18 Files are laid out to avoid unnecessary function declarations. So for
19 example, every function add_cmd calls occurs before add_cmd in this file.
21 add_cmd() is called on each line of sed command text (from a file or from
22 the command line). It calls get_address() and parse_cmd_args(). The
23 resulting sed_cmd_t structures are appended to a linked list
24 (G.sed_cmd_head/G.sed_cmd_tail).
26 add_input_file() adds a FILE * to the list of input files. We need to
27 know all input sources ahead of time to find the last line for the $ match.
29 process_files() does actual sedding, reading data lines from each input FILE *
30 (which could be stdin) and applying the sed command list (sed_cmd_head) to
31 each of the resulting lines.
33 sed_main() is where external code calls into this, with a command line.
38 Supported features and commands in this version of sed:
41 - address matching: num|/matchstr/[,num|/matchstr/|$]command
42 - commands: (p)rint, (d)elete, (s)ubstitue (with g & I flags)
43 - edit commands: (a)ppend, (i)nsert, (c)hange
44 - file commands: (r)ead
45 - backreferences in substitution expressions (\0, \1, \2...\9)
46 - grouped commands: {cmd1;cmd2}
47 - transliteration (y/source-chars/dest-chars/)
48 - pattern space hold space storing / swapping (g, h, x)
49 - labels / branching (: label, b, t, T)
51 (Note: Specifying an address (range) to match is *optional*; commands
52 default to the whole pattern space if no specific address match was
56 - Create a wrapper around regex to make libc's regex conform with sed
58 Reference http://www.opengroup.org/onlinepubs/007904975/utilities/sed.html
64 /* Each sed command turns into one of these structures. */
65 typedef struct sed_cmd_s {
66 /* Ordered by alignment requirements: currently 36 bytes on x86 */
67 struct sed_cmd_s *next; /* Next command (linked list, NULL terminated) */
70 regex_t *beg_match; /* sed -e '/match/cmd' */
71 regex_t *end_match; /* sed -e '/match/,/end_match/cmd' */
72 regex_t *sub_match; /* For 's/sub_match/string/' */
73 int beg_line; /* 'sed 1p' 0 == apply commands to all lines */
74 int end_line; /* 'sed 1,3p' 0 == one line only. -1 = last line ($) */
76 FILE *sw_file; /* File (sw) command writes to, -1 for none. */
77 char *string; /* Data string for (saicytb) commands. */
79 unsigned short which_match; /* (s) Which match to replace (0 for all) */
81 /* Bitfields (gcc won't group them if we don't) */
82 unsigned invert:1; /* the '!' after the address */
83 unsigned in_match:1; /* Next line also included in match? */
84 unsigned sub_p:1; /* (s) print option */
86 char sw_last_char; /* Last line written by (sw) had no '\n' */
89 char cmd; /* The command char: abcdDgGhHilnNpPqrstwxy:={} */
92 static const char semicolon_whitespace[] = "; \n\r\t\v";
96 int be_quiet, regex_type;
98 char *outname, *hold_space;
100 /* List of input files */
101 int input_file_count, current_input_file;
102 FILE **input_file_list;
104 regmatch_t regmatch[10];
105 regex_t *previous_regex_ptr;
107 /* linked list of sed commands */
108 sed_cmd_t sed_cmd_head, *sed_cmd_tail;
110 /* Linked list of append lines */
111 llist_t *append_head;
116 char *buf; /* Space to hold string */
117 int idx; /* Space used */
118 int len; /* Space allocated */
122 #define G (*(struct globals*)&bb_common_bufsiz1)
124 #if ENABLE_FEATURE_CLEAN_UP
125 static void sed_free_and_close_stuff(void)
127 sed_cmd_t *sed_cmd = G.sed_cmd_head.next;
129 llist_free(G.append_head, free);
132 sed_cmd_t *sed_cmd_next = sed_cmd->next;
134 if (sed_cmd->sw_file)
135 xprint_and_close_file(sed_cmd->sw_file);
137 if (sed_cmd->beg_match) {
138 regfree(sed_cmd->beg_match);
139 free(sed_cmd->beg_match);
141 if (sed_cmd->end_match) {
142 regfree(sed_cmd->end_match);
143 free(sed_cmd->end_match);
145 if (sed_cmd->sub_match) {
146 regfree(sed_cmd->sub_match);
147 free(sed_cmd->sub_match);
149 free(sed_cmd->string);
151 sed_cmd = sed_cmd_next;
154 if (G.hold_space) free(G.hold_space);
156 while (G.current_input_file < G.input_file_count)
157 fclose(G.input_file_list[G.current_input_file++]);
160 void sed_free_and_close_stuff(void);
163 /* If something bad happens during -i operation, delete temp file */
165 static void cleanup_outname(void)
167 if (G.outname) unlink(G.outname);
170 /* strdup, replacing "\n" with '\n', and "\delimiter" with 'delimiter' */
172 static void parse_escapes(char *dest, const char *string, int len, char from, char to)
177 if (string[i] == '\\') {
178 if (!to || string[i+1] == from) {
179 *dest++ = to ? to : string[i+1];
183 *dest++ = string[i++];
185 *dest++ = string[i++];
190 static char *copy_parsing_escapes(const char *string, int len)
192 char *dest = xmalloc(len + 1);
194 parse_escapes(dest, string, len, 'n', '\n');
200 * index_of_next_unescaped_regexp_delim - walks left to right through a string
201 * beginning at a specified index and returns the index of the next regular
202 * expression delimiter (typically a forward * slash ('/')) not preceded by
203 * a backslash ('\'). A negative delimiter disables square bracket checking.
205 static int index_of_next_unescaped_regexp_delim(int delimiter, const char *str)
214 delimiter = -delimiter;
217 for (; (ch = str[idx]); idx++) {
219 if (ch == ']' && !(bracket == idx - 1 || (bracket == idx - 2
220 && str[idx - 1] == '^')))
226 else if (bracket == -1 && ch == '[')
228 else if (ch == delimiter)
232 /* if we make it to here, we've hit the end of the string */
233 bb_error_msg_and_die("unmatched '%c'", delimiter);
237 * Returns the index of the third delimiter
239 static int parse_regex_delim(const char *cmdstr, char **match, char **replace)
241 const char *cmdstr_ptr = cmdstr;
245 /* verify that the 's' or 'y' is followed by something. That something
246 * (typically a 'slash') is now our regexp delimiter... */
248 bb_error_msg_and_die("bad format in substitution expression");
249 delimiter = *cmdstr_ptr++;
251 /* save the match string */
252 idx = index_of_next_unescaped_regexp_delim(delimiter, cmdstr_ptr);
253 *match = copy_parsing_escapes(cmdstr_ptr, idx);
255 /* save the replacement string */
256 cmdstr_ptr += idx + 1;
257 idx = index_of_next_unescaped_regexp_delim(-delimiter, cmdstr_ptr);
258 *replace = copy_parsing_escapes(cmdstr_ptr, idx);
260 return ((cmdstr_ptr - cmdstr) + idx);
264 * returns the index in the string just past where the address ends.
266 static int get_address(const char *my_str, int *linenum, regex_t ** regex)
268 const char *pos = my_str;
270 if (isdigit(*my_str)) {
271 *linenum = strtol(my_str, (char**)&pos, 10);
272 /* endstr shouldnt ever equal NULL */
273 } else if (*my_str == '$') {
276 } else if (*my_str == '/' || *my_str == '\\') {
282 if (*my_str == '\\') delimiter = *++pos;
283 next = index_of_next_unescaped_regexp_delim(delimiter, ++pos);
284 temp = copy_parsing_escapes(pos, next);
285 *regex = xmalloc(sizeof(regex_t));
286 xregcomp(*regex, temp, G.regex_type|REG_NEWLINE);
288 /* Move position to next character after last delimiter */
294 /* Grab a filename. Whitespace at start is skipped, then goes to EOL. */
295 static int parse_file_cmd(sed_cmd_t *sed_cmd, const char *filecmdstr, char **retval)
297 int start = 0, idx, hack = 0;
299 /* Skip whitespace, then grab filename to end of line */
300 while (isspace(filecmdstr[start]))
303 while (filecmdstr[idx] && filecmdstr[idx] != '\n')
306 /* If lines glued together, put backslash back. */
307 if (filecmdstr[idx] == '\n')
310 bb_error_msg_and_die("empty filename");
311 *retval = xstrndup(filecmdstr+start, idx-start+hack+1);
313 (*retval)[idx] = '\\';
318 static int parse_subst_cmd(sed_cmd_t *sed_cmd, const char *substr)
320 int cflags = G.regex_type;
325 * A substitution command should look something like this:
326 * s/match/replace/ #gIpw
330 idx = parse_regex_delim(substr, &match, &sed_cmd->string);
332 /* determine the number of back references in the match string */
333 /* Note: we compute this here rather than in the do_subst_command()
334 * function to save processor time, at the expense of a little more memory
335 * (4 bits) per sed_cmd */
337 /* process the flags */
339 sed_cmd->which_match = 1;
340 while (substr[++idx]) {
341 /* Parse match number */
342 if (isdigit(substr[idx])) {
343 if (match[0] != '^') {
344 /* Match 0 treated as all, multiple matches we take the last one. */
345 const char *pos = substr + idx;
346 /* FIXME: error check? */
347 sed_cmd->which_match = (unsigned short)strtol(substr+idx, (char**) &pos, 10);
353 if (isspace(substr[idx])) continue;
355 switch (substr[idx]) {
356 /* Replace all occurrences */
358 if (match[0] != '^') sed_cmd->which_match = 0;
360 /* Print pattern space */
368 idx += parse_file_cmd(sed_cmd, substr+idx, &temp);
371 /* Ignore case (gnu exension) */
377 while (substr[++idx]) /*skip all*/;
384 bb_error_msg_and_die("bad option in substitution expression");
388 /* compile the match string into a regex */
389 if (*match != '\0') {
390 /* If match is empty, we use last regex used at runtime */
391 sed_cmd->sub_match = xmalloc(sizeof(regex_t));
392 xregcomp(sed_cmd->sub_match, match, cflags);
400 * Process the commands arguments
402 static const char *parse_cmd_args(sed_cmd_t *sed_cmd, const char *cmdstr)
404 /* handle (s)ubstitution command */
405 if (sed_cmd->cmd == 's')
406 cmdstr += parse_subst_cmd(sed_cmd, cmdstr);
407 /* handle edit cmds: (a)ppend, (i)nsert, and (c)hange */
408 else if (strchr("aic", sed_cmd->cmd)) {
409 if ((sed_cmd->end_line || sed_cmd->end_match) && sed_cmd->cmd != 'c')
411 ("only a beginning address can be specified for edit commands");
413 if (*cmdstr == '\n' || *cmdstr == '\\') {
416 } else if (isspace(*cmdstr))
421 sed_cmd->string = xstrdup(cmdstr);
422 parse_escapes(sed_cmd->string, sed_cmd->string, strlen(cmdstr), 0, 0);
423 cmdstr += strlen(cmdstr);
424 /* handle file cmds: (r)ead */
425 } else if (strchr("rw", sed_cmd->cmd)) {
426 if (sed_cmd->end_line || sed_cmd->end_match)
427 bb_error_msg_and_die("command only uses one address");
428 cmdstr += parse_file_cmd(sed_cmd, cmdstr, &sed_cmd->string);
429 if (sed_cmd->cmd == 'w') {
430 sed_cmd->sw_file = xfopen(sed_cmd->string, "w");
431 sed_cmd->sw_last_char = '\n';
433 /* handle branch commands */
434 } else if (strchr(":btT", sed_cmd->cmd)) {
437 cmdstr = skip_whitespace(cmdstr);
438 length = strcspn(cmdstr, semicolon_whitespace);
440 sed_cmd->string = xstrndup(cmdstr, length);
444 /* translation command */
445 else if (sed_cmd->cmd == 'y') {
446 char *match, *replace;
449 cmdstr += parse_regex_delim(cmdstr, &match, &replace)+1;
450 /* \n already parsed, but \delimiter needs unescaping. */
451 parse_escapes(match, match, strlen(match), i, i);
452 parse_escapes(replace, replace, strlen(replace), i, i);
454 sed_cmd->string = xzalloc((strlen(match) + 1) * 2);
455 for (i = 0; match[i] && replace[i]; i++) {
456 sed_cmd->string[i*2] = match[i];
457 sed_cmd->string[i*2+1] = replace[i];
462 /* if it wasnt a single-letter command that takes no arguments
463 * then it must be an invalid command.
465 else if (strchr("dDgGhHlnNpPqx={}", sed_cmd->cmd) == 0) {
466 bb_error_msg_and_die("unsupported command %c", sed_cmd->cmd);
469 /* give back whatever's left over */
474 /* Parse address+command sets, skipping comment lines. */
476 static void add_cmd(const char *cmdstr)
481 /* Append this line to any unfinished line from last time. */
482 if (G.add_cmd_line) {
483 char *tp = xasprintf("%s\n%s", G.add_cmd_line, cmdstr);
484 free(G.add_cmd_line);
485 cmdstr = G.add_cmd_line = tp;
488 /* If this line ends with backslash, request next line. */
489 temp = strlen(cmdstr);
490 if (temp && cmdstr[--temp] == '\\') {
492 G.add_cmd_line = xstrdup(cmdstr);
493 G.add_cmd_line[temp] = '\0';
497 /* Loop parsing all commands in this line. */
499 /* Skip leading whitespace and semicolons */
500 cmdstr += strspn(cmdstr, semicolon_whitespace);
502 /* If no more commands, exit. */
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')
510 cmdstr = strpbrk(cmdstr, "\n\r");
516 * format is: [addr][,addr][!]cmd
521 sed_cmd = xzalloc(sizeof(sed_cmd_t));
523 /* first part (if present) is an address: either a '$', a number or a /regex/ */
524 cmdstr += get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
526 /* second part (if present) will begin with a comma */
527 if (*cmdstr == ',') {
531 idx = get_address(cmdstr, &sed_cmd->end_line, &sed_cmd->end_match);
533 bb_error_msg_and_die("no address after comma");
537 /* skip whitespace before the command */
538 cmdstr = skip_whitespace(cmdstr);
540 /* Check for inversion flag */
541 if (*cmdstr == '!') {
545 /* skip whitespace before the command */
546 cmdstr = skip_whitespace(cmdstr);
549 /* last part (mandatory) will be a command */
551 bb_error_msg_and_die("missing command");
552 sed_cmd->cmd = *(cmdstr++);
553 cmdstr = parse_cmd_args(sed_cmd, cmdstr);
555 /* Add the command to the command array */
556 G.sed_cmd_tail->next = sed_cmd;
557 G.sed_cmd_tail = G.sed_cmd_tail->next;
560 /* If we glued multiple lines together, free the memory. */
561 free(G.add_cmd_line);
562 G.add_cmd_line = NULL;
565 /* Append to a string, reallocating memory as necessary. */
569 static void pipe_putc(char c)
571 if (G.pipeline.idx == G.pipeline.len) {
572 G.pipeline.buf = xrealloc(G.pipeline.buf,
573 G.pipeline.len + PIPE_GROW);
574 G.pipeline.len += PIPE_GROW;
576 G.pipeline.buf[G.pipeline.idx++] = c;
579 static void do_subst_w_backrefs(char *line, char *replace)
583 /* go through the replacement string */
584 for (i = 0; replace[i]; i++) {
585 /* if we find a backreference (\1, \2, etc.) print the backref'ed * text */
586 if (replace[i] == '\\') {
587 unsigned backref = replace[++i] - '0';
589 /* print out the text held in G.regmatch[backref] */
590 if (G.regmatch[backref].rm_so != -1) {
591 j = G.regmatch[backref].rm_so;
592 while (j < G.regmatch[backref].rm_eo)
593 pipe_putc(line[j++]);
597 /* I _think_ it is impossible to get '\' to be
598 * the last char in replace string. Thus we dont check
599 * for replace[i] == NUL. (counterexample anyone?) */
600 /* if we find a backslash escaped character, print the character */
601 pipe_putc(replace[i]);
604 /* if we find an unescaped '&' print out the whole matched text. */
605 if (replace[i] == '&') {
606 j = G.regmatch[0].rm_so;
607 while (j < G.regmatch[0].rm_eo)
608 pipe_putc(line[j++]);
611 /* Otherwise just output the character. */
612 pipe_putc(replace[i]);
616 static int do_subst_command(sed_cmd_t *sed_cmd, char **line)
618 char *oldline = *line;
621 regex_t *current_regex;
623 /* Handle empty regex. */
624 if (sed_cmd->sub_match == NULL) {
625 current_regex = G.previous_regex_ptr;
627 bb_error_msg_and_die("no previous regexp");
629 G.previous_regex_ptr = current_regex = sed_cmd->sub_match;
631 /* Find the first match */
632 if (REG_NOMATCH == regexec(current_regex, oldline, 10, G.regmatch, 0))
635 /* Initialize temporary output buffer. */
636 G.pipeline.buf = xmalloc(PIPE_GROW);
637 G.pipeline.len = PIPE_GROW;
640 /* Now loop through, substituting for matches */
644 /* Work around bug in glibc regexec, demonstrated by:
645 echo " a.b" | busybox sed 's [^ .]* x g'
646 The match_count check is so not to break
647 echo "hi" | busybox sed 's/^/!/g' */
648 if (!G.regmatch[0].rm_so && !G.regmatch[0].rm_eo && match_count) {
649 pipe_putc(*oldline++);
655 /* If we aren't interested in this match, output old line to
656 end of match and continue */
657 if (sed_cmd->which_match && sed_cmd->which_match != match_count) {
658 for (i = 0; i < G.regmatch[0].rm_eo; i++)
659 pipe_putc(*oldline++);
663 /* print everything before the match */
664 for (i = 0; i < G.regmatch[0].rm_so; i++)
665 pipe_putc(oldline[i]);
667 /* then print the substitution string */
668 do_subst_w_backrefs(oldline, sed_cmd->string);
670 /* advance past the match */
671 oldline += G.regmatch[0].rm_eo;
672 /* flag that something has changed */
675 /* if we're not doing this globally, get out now */
676 if (sed_cmd->which_match) break;
677 } while (*oldline && (regexec(current_regex, oldline, 10, G.regmatch, 0) != REG_NOMATCH));
679 /* Copy rest of string into output pipeline */
682 pipe_putc(*oldline++);
686 *line = G.pipeline.buf;
690 /* Set command pointer to point to this label. (Does not handle null label.) */
691 static sed_cmd_t *branch_to(char *label)
695 for (sed_cmd = G.sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
696 if (sed_cmd->cmd == ':' && sed_cmd->string && !strcmp(sed_cmd->string, label)) {
700 bb_error_msg_and_die("can't find label for jump to '%s'", label);
703 static void append(char *s)
705 llist_add_to_end(&G.append_head, xstrdup(s));
708 static void flush_append(void)
712 /* Output appended lines. */
713 while ((data = (char *)llist_pop(&G.append_head))) {
714 fprintf(G.nonstdout, "%s\n", data);
719 static void add_input_file(FILE *file)
721 G.input_file_list = xrealloc(G.input_file_list,
722 (G.input_file_count + 1) * sizeof(FILE *));
723 G.input_file_list[G.input_file_count++] = file;
726 /* Get next line of input from G.input_file_list, flushing append buffer and
727 * noting if we ran out of files without a newline on the last line we read.
733 static char *get_next_line(char *gets_char)
741 /* will be returned if last line in the file
742 * doesn't end with either '\n' or '\0' */
744 while (G.current_input_file < G.input_file_count) {
745 FILE *fp = G.input_file_list[G.current_input_file];
746 /* Read line up to a newline or NUL byte, inclusive,
747 * return malloc'ed char[]. length of the chunk read
748 * is stored in len. NULL if EOF/error */
749 temp = bb_get_chunk_from_file(fp, &len);
751 /* len > 0 here, it's ok to do temp[len-1] */
752 char c = temp[len-1];
753 if (c == '\n' || c == '\0') {
764 /* else we put NO_EOL_CHAR into *gets_char */
767 /* NB: I had the idea of peeking next file(s) and returning
768 * NO_EOL_CHAR only if it is the *last* non-empty
769 * input file. But there is a case where this won't work:
770 * file1: "a woo\nb woo"
771 * file2: "c no\nd no"
772 * sed -ne 's/woo/bang/p' input1 input2 => "a bang\nb bang"
773 * (note: *no* newline after "b bang"!) */
775 /* Close this file and advance to next one */
777 G.current_input_file++;
783 /* Output line of text. */
785 * The tricks with NO_EOL_CHAR and last_puts_char are there to emulate gnu sed.
786 * Without them, we had this:
790 * sed "s/i/z/" z1 z2 znull | hexdump -vC
793 * 00000000 74 68 7a 6e 67 79 0a 61 67 61 7a 6e |thzngy.agazn|
795 * 00000000 74 68 7a 6e 67 79 61 67 61 7a 6e |thzngyagazn|
797 static void puts_maybe_newline(char *s, FILE *file, char *last_puts_char, char last_gets_char)
799 char lpc = *last_puts_char;
801 /* Need to insert a '\n' between two files because first file's
802 * last line wasn't terminated? */
803 if (lpc != '\n' && lpc != '\0') {
809 /* 'x' - just something which is not '\n', '\0' or NO_EOL_CHAR */
813 /* had trailing '\0' and it was last char of file? */
814 if (last_gets_char == LAST_IS_NUL) {
818 /* had trailing '\n' or '\0'? */
819 if (last_gets_char != NO_EOL_CHAR) {
820 fputc(last_gets_char, file);
821 lpc = last_gets_char;
825 xfunc_error_retval = 4; /* It's what gnu sed exits with... */
826 bb_error_msg_and_die(bb_msg_write_error);
828 *last_puts_char = lpc;
831 #define sed_puts(s, n) (puts_maybe_newline(s, G.nonstdout, &last_puts_char, n))
833 /* Process all the lines in all the files */
835 static void process_files(void)
837 char *pattern_space, *next_line;
839 char last_puts_char = '\n';
840 char last_gets_char, next_gets_char;
845 next_line = get_next_line(&next_gets_char);
847 /* go through every line in each file */
851 /* Advance to next line. Stop if out of lines. */
852 pattern_space = next_line;
853 if (!pattern_space) return;
854 last_gets_char = next_gets_char;
856 /* Read one line in advance so we can act on the last line,
858 next_line = get_next_line(&next_gets_char);
861 /* for every line, go through all the commands */
862 for (sed_cmd = G.sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
863 int old_matched, matched;
865 old_matched = sed_cmd->in_match;
867 /* Determine if this command matches this line: */
869 /* Are we continuing a previous multi-line match? */
870 sed_cmd->in_match = sed_cmd->in_match
871 /* Or is no range necessary? */
872 || (!sed_cmd->beg_line && !sed_cmd->end_line
873 && !sed_cmd->beg_match && !sed_cmd->end_match)
874 /* Or did we match the start of a numerical range? */
875 || (sed_cmd->beg_line > 0 && (sed_cmd->beg_line == linenum))
876 /* Or does this line match our begin address regex? */
877 || (sed_cmd->beg_match &&
878 !regexec(sed_cmd->beg_match, pattern_space, 0, NULL, 0))
879 /* Or did we match last line of input? */
880 || (sed_cmd->beg_line == -1 && next_line == NULL);
882 /* Snapshot the value */
884 matched = sed_cmd->in_match;
886 /* Is this line the end of the current match? */
889 sed_cmd->in_match = !(
890 /* has the ending line come, or is this a single address command? */
892 sed_cmd->end_line == -1 ?
894 : (sed_cmd->end_line <= linenum)
895 : !sed_cmd->end_match
897 /* or does this line matches our last address regex */
898 || (sed_cmd->end_match && old_matched
899 && (regexec(sed_cmd->end_match,
900 pattern_space, 0, NULL, 0) == 0))
904 /* Skip blocks of commands we didn't match. */
905 if (sed_cmd->cmd == '{') {
906 if (sed_cmd->invert ? matched : !matched) {
907 while (sed_cmd->cmd != '}') {
908 sed_cmd = sed_cmd->next;
910 bb_error_msg_and_die("unterminated {");
916 /* Okay, so did this line match? */
917 if (sed_cmd->invert ? !matched : matched) {
918 /* Update last used regex in case a blank substitute BRE is found */
919 if (sed_cmd->beg_match) {
920 G.previous_regex_ptr = sed_cmd->beg_match;
924 switch (sed_cmd->cmd) {
926 /* Print line number */
928 fprintf(G.nonstdout, "%d\n", linenum);
931 /* Write the current pattern space up to the first newline */
934 char *tmp = strchr(pattern_space, '\n');
938 /* TODO: explain why '\n' below */
939 sed_puts(pattern_space, '\n');
946 /* Write the current pattern space to output */
948 /* NB: we print this _before_ the last line
949 * (of current file) is printed. Even if
950 * that line is nonterminated, we print
951 * '\n' here (gnu sed does the same) */
952 sed_puts(pattern_space, '\n');
954 /* Delete up through first newline */
957 char *tmp = strchr(pattern_space, '\n');
960 tmp = xstrdup(tmp+1);
966 /* discard this line. */
970 /* Substitute with regex */
972 if (!do_subst_command(sed_cmd, &pattern_space))
976 /* handle p option */
978 sed_puts(pattern_space, last_gets_char);
979 /* handle w option */
980 if (sed_cmd->sw_file)
982 pattern_space, sed_cmd->sw_file,
983 &sed_cmd->sw_last_char, last_gets_char);
986 /* Append line to linked list to be printed later */
988 append(sed_cmd->string);
991 /* Insert text before this line */
993 sed_puts(sed_cmd->string, '\n');
996 /* Cut and paste text (replace) */
998 /* Only triggers on last line of a matching range. */
999 if (!sed_cmd->in_match)
1000 sed_puts(sed_cmd->string, NO_EOL_CHAR);
1003 /* Read file, append contents to output */
1008 rfile = fopen(sed_cmd->string, "r");
1012 while ((line = xmalloc_getline(rfile))
1015 xprint_and_close_file(rfile);
1021 /* Write pattern space to file. */
1024 pattern_space, sed_cmd->sw_file,
1025 &sed_cmd->sw_last_char, last_gets_char);
1028 /* Read next line from input */
1031 sed_puts(pattern_space, last_gets_char);
1033 free(pattern_space);
1034 pattern_space = next_line;
1035 last_gets_char = next_gets_char;
1036 next_line = get_next_line(&next_gets_char);
1042 /* Quit. End of script, end of input. */
1044 /* Exit the outer while loop */
1047 goto discard_commands;
1049 /* Append the next line to the current line */
1053 /* If no next line, jump to end of script and exit. */
1054 if (next_line == NULL) {
1055 /* Jump to end of script and exit */
1059 /* append next_line, read new next_line. */
1061 len = strlen(pattern_space);
1062 pattern_space = realloc(pattern_space, len + strlen(next_line) + 2);
1063 pattern_space[len] = '\n';
1064 strcpy(pattern_space + len+1, next_line);
1065 last_gets_char = next_gets_char;
1066 next_line = get_next_line(&next_gets_char);
1071 /* Test/branch if substitution occurred */
1073 if (!substituted) break;
1076 /* Test/branch if substitution didn't occur */
1078 if (substituted) break;
1080 /* Branch to label */
1082 if (!sed_cmd->string) goto discard_commands;
1083 else sed_cmd = branch_to(sed_cmd->string);
1085 /* Transliterate characters */
1090 for (i = 0; pattern_space[i]; i++) {
1091 for (j = 0; sed_cmd->string[j]; j += 2) {
1092 if (pattern_space[i] == sed_cmd->string[j]) {
1093 pattern_space[i] = sed_cmd->string[j + 1];
1101 case 'g': /* Replace pattern space with hold space */
1102 free(pattern_space);
1103 pattern_space = xstrdup(G.hold_space ? G.hold_space : "");
1105 case 'G': /* Append newline and hold space to pattern space */
1107 int pattern_space_size = 2;
1108 int hold_space_size = 0;
1111 pattern_space_size += strlen(pattern_space);
1113 hold_space_size = strlen(G.hold_space);
1114 pattern_space = xrealloc(pattern_space,
1115 pattern_space_size + hold_space_size);
1116 if (pattern_space_size == 2)
1117 pattern_space[0] = 0;
1118 strcat(pattern_space, "\n");
1120 strcat(pattern_space, G.hold_space);
1121 last_gets_char = '\n';
1125 case 'h': /* Replace hold space with pattern space */
1127 G.hold_space = xstrdup(pattern_space);
1129 case 'H': /* Append newline and pattern space to hold space */
1131 int hold_space_size = 2;
1132 int pattern_space_size = 0;
1135 hold_space_size += strlen(G.hold_space);
1137 pattern_space_size = strlen(pattern_space);
1138 G.hold_space = xrealloc(G.hold_space,
1139 hold_space_size + pattern_space_size);
1141 if (hold_space_size == 2)
1143 strcat(G.hold_space, "\n");
1145 strcat(G.hold_space, pattern_space);
1149 case 'x': /* Exchange hold and pattern space */
1151 char *tmp = pattern_space;
1152 pattern_space = G.hold_space ? : xzalloc(1);
1153 last_gets_char = '\n';
1162 * exit point from sedding...
1165 /* we will print the line unless we were told to be quiet ('-n')
1166 or if the line was suppressed (ala 'd'elete) */
1168 sed_puts(pattern_space, last_gets_char);
1170 /* Delete and such jump here. */
1173 free(pattern_space);
1178 /* It is possible to have a command line argument with embedded
1179 * newlines. This counts as multiple command lines.
1180 * However, newline can be escaped: 's/e/z\<newline>z/'
1181 * We check for this.
1184 static void add_cmd_block(char *cmdstr)
1188 cmdstr = sv = xstrdup(cmdstr);
1190 eol = strchr(cmdstr, '\n');
1193 /* Count preceding slashes */
1197 while (sl != cmdstr && *--sl == '\\')
1199 /* Odd number of preceding slashes - newline is escaped */
1202 eol = strchr(eol, '\n');
1213 void BUG_sed_globals_too_big(void);
1215 int sed_main(int argc, char **argv);
1216 int sed_main(int argc, char **argv)
1219 OPT_in_place = 1 << 0,
1222 llist_t *opt_e, *opt_f;
1223 int status = EXIT_SUCCESS;
1225 if (sizeof(struct globals) > sizeof(bb_common_bufsiz1))
1226 BUG_sed_globals_too_big();
1228 G.sed_cmd_tail = &G.sed_cmd_head;
1230 /* destroy command strings on exit */
1231 if (ENABLE_FEATURE_CLEAN_UP) atexit(sed_free_and_close_stuff);
1233 /* Lie to autoconf when it starts asking stupid questions. */
1234 if (argc == 2 && !strcmp(argv[1], "--version")) {
1235 puts("This is not GNU sed version 4.0");
1239 /* do normal option parsing */
1240 opt_e = opt_f = NULL;
1241 opt_complementary = "e::f::" /* can occur multiple times */
1242 "nn"; /* count -n */
1243 opt = getopt32(argc, argv, "irne:f:", &opt_e, &opt_f,
1244 &G.be_quiet); /* counter for -n */
1247 if (opt & OPT_in_place) { // -i
1248 atexit(cleanup_outname);
1250 if (opt & 0x2) G.regex_type |= REG_EXTENDED; // -r
1251 //if (opt & 0x4) G.be_quiet++; // -n
1252 while (opt_e) { // -e
1253 add_cmd_block(opt_e->data);
1254 opt_e = opt_e->link;
1255 /* we leak opt_e here... */
1257 while (opt_f) { // -f
1260 cmdfile = xfopen(opt_f->data, "r");
1261 while ((line = xmalloc_getline(cmdfile)) != NULL) {
1266 opt_f = opt_f->link;
1267 /* we leak opt_f here... */
1269 /* if we didn't get a pattern from -e or -f, use argv[0] */
1270 if (!(opt & 0x18)) {
1273 add_cmd_block(*argv++);
1276 /* Flush any unfinished commands. */
1279 /* By default, we write to stdout */
1280 G.nonstdout = stdout;
1282 /* argv[0..(argc-1)] should be names of file to process. If no
1283 * files were specified or '-' was specified, take input from stdin.
1284 * Otherwise, we process all the files specified. */
1285 if (argv[0] == NULL) {
1286 if (opt & OPT_in_place)
1287 bb_error_msg_and_die(bb_msg_requires_arg, "-i");
1288 add_input_file(stdin);
1294 for (i = 0; i < argc; i++) {
1295 struct stat statbuf;
1298 if (LONE_DASH(argv[i]) && !(opt & OPT_in_place)) {
1299 add_input_file(stdin);
1303 file = fopen_or_warn(argv[i], "r");
1305 status = EXIT_FAILURE;
1308 if (!(opt & OPT_in_place)) {
1309 add_input_file(file);
1313 G.outname = xasprintf("%sXXXXXX", argv[i]);
1314 nonstdoutfd = mkstemp(G.outname);
1315 if (-1 == nonstdoutfd)
1316 bb_perror_msg_and_die("cannot create temp file %s", G.outname);
1317 G.nonstdout = fdopen(nonstdoutfd, "w");
1319 /* Set permissions of output file */
1321 fstat(fileno(file), &statbuf);
1322 fchmod(nonstdoutfd, statbuf.st_mode);
1323 add_input_file(file);
1325 fclose(G.nonstdout);
1327 G.nonstdout = stdout;
1328 /* unlink(argv[i]); */
1329 // FIXME: error check / message?
1330 rename(G.outname, argv[i]);
1334 if (G.input_file_count > G.current_input_file)