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[] ALIGN1 = "; \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 */
121 #define G (*(struct globals*)&bb_common_bufsiz1)
122 void BUG_sed_globals_too_big(void);
123 #define INIT_G() do { \
124 if (sizeof(struct globals) > COMMON_BUFSIZE) \
125 BUG_sed_globals_too_big(); \
126 G.sed_cmd_tail = &G.sed_cmd_head; \
130 #if ENABLE_FEATURE_CLEAN_UP
131 static void sed_free_and_close_stuff(void)
133 sed_cmd_t *sed_cmd = G.sed_cmd_head.next;
135 llist_free(G.append_head, free);
138 sed_cmd_t *sed_cmd_next = sed_cmd->next;
140 if (sed_cmd->sw_file)
141 xprint_and_close_file(sed_cmd->sw_file);
143 if (sed_cmd->beg_match) {
144 regfree(sed_cmd->beg_match);
145 free(sed_cmd->beg_match);
147 if (sed_cmd->end_match) {
148 regfree(sed_cmd->end_match);
149 free(sed_cmd->end_match);
151 if (sed_cmd->sub_match) {
152 regfree(sed_cmd->sub_match);
153 free(sed_cmd->sub_match);
155 free(sed_cmd->string);
157 sed_cmd = sed_cmd_next;
160 if (G.hold_space) free(G.hold_space);
162 while (G.current_input_file < G.input_file_count)
163 fclose(G.input_file_list[G.current_input_file++]);
166 void sed_free_and_close_stuff(void);
169 /* If something bad happens during -i operation, delete temp file */
171 static void cleanup_outname(void)
173 if (G.outname) unlink(G.outname);
176 /* strdup, replacing "\n" with '\n', and "\delimiter" with 'delimiter' */
178 static void parse_escapes(char *dest, const char *string, int len, char from, char to)
183 if (string[i] == '\\') {
184 if (!to || string[i+1] == from) {
185 *dest++ = to ? to : string[i+1];
189 *dest++ = string[i++];
191 *dest++ = string[i++];
196 static char *copy_parsing_escapes(const char *string, int len)
198 char *dest = xmalloc(len + 1);
200 parse_escapes(dest, string, len, 'n', '\n');
206 * index_of_next_unescaped_regexp_delim - walks left to right through a string
207 * beginning at a specified index and returns the index of the next regular
208 * expression delimiter (typically a forward * slash ('/')) not preceded by
209 * a backslash ('\'). A negative delimiter disables square bracket checking.
211 static int index_of_next_unescaped_regexp_delim(int delimiter, const char *str)
220 delimiter = -delimiter;
223 for (; (ch = str[idx]); idx++) {
225 if (ch == ']' && !(bracket == idx - 1 || (bracket == idx - 2
226 && str[idx - 1] == '^')))
232 else if (bracket == -1 && ch == '[')
234 else if (ch == delimiter)
238 /* if we make it to here, we've hit the end of the string */
239 bb_error_msg_and_die("unmatched '%c'", delimiter);
243 * Returns the index of the third delimiter
245 static int parse_regex_delim(const char *cmdstr, char **match, char **replace)
247 const char *cmdstr_ptr = cmdstr;
251 /* verify that the 's' or 'y' is followed by something. That something
252 * (typically a 'slash') is now our regexp delimiter... */
254 bb_error_msg_and_die("bad format in substitution expression");
255 delimiter = *cmdstr_ptr++;
257 /* save the match string */
258 idx = index_of_next_unescaped_regexp_delim(delimiter, cmdstr_ptr);
259 *match = copy_parsing_escapes(cmdstr_ptr, idx);
261 /* save the replacement string */
262 cmdstr_ptr += idx + 1;
263 idx = index_of_next_unescaped_regexp_delim(-delimiter, cmdstr_ptr);
264 *replace = copy_parsing_escapes(cmdstr_ptr, idx);
266 return ((cmdstr_ptr - cmdstr) + idx);
270 * returns the index in the string just past where the address ends.
272 static int get_address(const char *my_str, int *linenum, regex_t ** regex)
274 const char *pos = my_str;
276 if (isdigit(*my_str)) {
277 *linenum = strtol(my_str, (char**)&pos, 10);
278 /* endstr shouldnt ever equal NULL */
279 } else if (*my_str == '$') {
282 } else if (*my_str == '/' || *my_str == '\\') {
288 if (*my_str == '\\') delimiter = *++pos;
289 next = index_of_next_unescaped_regexp_delim(delimiter, ++pos);
290 temp = copy_parsing_escapes(pos, next);
291 *regex = xmalloc(sizeof(regex_t));
292 xregcomp(*regex, temp, G.regex_type|REG_NEWLINE);
294 /* Move position to next character after last delimiter */
300 /* Grab a filename. Whitespace at start is skipped, then goes to EOL. */
301 static int parse_file_cmd(sed_cmd_t *sed_cmd, const char *filecmdstr, char **retval)
303 int start = 0, idx, hack = 0;
305 /* Skip whitespace, then grab filename to end of line */
306 while (isspace(filecmdstr[start]))
309 while (filecmdstr[idx] && filecmdstr[idx] != '\n')
312 /* If lines glued together, put backslash back. */
313 if (filecmdstr[idx] == '\n')
316 bb_error_msg_and_die("empty filename");
317 *retval = xstrndup(filecmdstr+start, idx-start+hack+1);
319 (*retval)[idx] = '\\';
324 static int parse_subst_cmd(sed_cmd_t *sed_cmd, const char *substr)
326 int cflags = G.regex_type;
331 * A substitution command should look something like this:
332 * s/match/replace/ #gIpw
336 idx = parse_regex_delim(substr, &match, &sed_cmd->string);
338 /* determine the number of back references in the match string */
339 /* Note: we compute this here rather than in the do_subst_command()
340 * function to save processor time, at the expense of a little more memory
341 * (4 bits) per sed_cmd */
343 /* process the flags */
345 sed_cmd->which_match = 1;
346 while (substr[++idx]) {
347 /* Parse match number */
348 if (isdigit(substr[idx])) {
349 if (match[0] != '^') {
350 /* Match 0 treated as all, multiple matches we take the last one. */
351 const char *pos = substr + idx;
352 /* FIXME: error check? */
353 sed_cmd->which_match = (unsigned short)strtol(substr+idx, (char**) &pos, 10);
359 if (isspace(substr[idx])) continue;
361 switch (substr[idx]) {
362 /* Replace all occurrences */
364 if (match[0] != '^') sed_cmd->which_match = 0;
366 /* Print pattern space */
374 idx += parse_file_cmd(sed_cmd, substr+idx, &temp);
377 /* Ignore case (gnu exension) */
383 while (substr[++idx]) /*skip all*/;
390 bb_error_msg_and_die("bad option in substitution expression");
394 /* compile the match string into a regex */
395 if (*match != '\0') {
396 /* If match is empty, we use last regex used at runtime */
397 sed_cmd->sub_match = xmalloc(sizeof(regex_t));
398 xregcomp(sed_cmd->sub_match, match, cflags);
406 * Process the commands arguments
408 static const char *parse_cmd_args(sed_cmd_t *sed_cmd, const char *cmdstr)
410 /* handle (s)ubstitution command */
411 if (sed_cmd->cmd == 's')
412 cmdstr += parse_subst_cmd(sed_cmd, cmdstr);
413 /* handle edit cmds: (a)ppend, (i)nsert, and (c)hange */
414 else if (strchr("aic", sed_cmd->cmd)) {
415 if ((sed_cmd->end_line || sed_cmd->end_match) && sed_cmd->cmd != 'c')
417 ("only a beginning address can be specified for edit commands");
419 if (*cmdstr == '\n' || *cmdstr == '\\') {
422 } else if (isspace(*cmdstr))
427 sed_cmd->string = xstrdup(cmdstr);
428 parse_escapes(sed_cmd->string, sed_cmd->string, strlen(cmdstr), 0, 0);
429 cmdstr += strlen(cmdstr);
430 /* handle file cmds: (r)ead */
431 } else if (strchr("rw", sed_cmd->cmd)) {
432 if (sed_cmd->end_line || sed_cmd->end_match)
433 bb_error_msg_and_die("command only uses one address");
434 cmdstr += parse_file_cmd(sed_cmd, cmdstr, &sed_cmd->string);
435 if (sed_cmd->cmd == 'w') {
436 sed_cmd->sw_file = xfopen(sed_cmd->string, "w");
437 sed_cmd->sw_last_char = '\n';
439 /* handle branch commands */
440 } else if (strchr(":btT", sed_cmd->cmd)) {
443 cmdstr = skip_whitespace(cmdstr);
444 length = strcspn(cmdstr, semicolon_whitespace);
446 sed_cmd->string = xstrndup(cmdstr, length);
450 /* translation command */
451 else if (sed_cmd->cmd == 'y') {
452 char *match, *replace;
455 cmdstr += parse_regex_delim(cmdstr, &match, &replace)+1;
456 /* \n already parsed, but \delimiter needs unescaping. */
457 parse_escapes(match, match, strlen(match), i, i);
458 parse_escapes(replace, replace, strlen(replace), i, i);
460 sed_cmd->string = xzalloc((strlen(match) + 1) * 2);
461 for (i = 0; match[i] && replace[i]; i++) {
462 sed_cmd->string[i*2] = match[i];
463 sed_cmd->string[i*2+1] = replace[i];
468 /* if it wasnt a single-letter command that takes no arguments
469 * then it must be an invalid command.
471 else if (strchr("dDgGhHlnNpPqx={}", sed_cmd->cmd) == 0) {
472 bb_error_msg_and_die("unsupported command %c", sed_cmd->cmd);
475 /* give back whatever's left over */
480 /* Parse address+command sets, skipping comment lines. */
482 static void add_cmd(const char *cmdstr)
487 /* Append this line to any unfinished line from last time. */
488 if (G.add_cmd_line) {
489 char *tp = xasprintf("%s\n%s", G.add_cmd_line, cmdstr);
490 free(G.add_cmd_line);
491 cmdstr = G.add_cmd_line = tp;
494 /* If this line ends with backslash, request next line. */
495 temp = strlen(cmdstr);
496 if (temp && cmdstr[--temp] == '\\') {
498 G.add_cmd_line = xstrdup(cmdstr);
499 G.add_cmd_line[temp] = '\0';
503 /* Loop parsing all commands in this line. */
505 /* Skip leading whitespace and semicolons */
506 cmdstr += strspn(cmdstr, semicolon_whitespace);
508 /* If no more commands, exit. */
511 /* if this is a comment, jump past it and keep going */
512 if (*cmdstr == '#') {
513 /* "#n" is the same as using -n on the command line */
514 if (cmdstr[1] == 'n')
516 cmdstr = strpbrk(cmdstr, "\n\r");
522 * format is: [addr][,addr][!]cmd
527 sed_cmd = xzalloc(sizeof(sed_cmd_t));
529 /* first part (if present) is an address: either a '$', a number or a /regex/ */
530 cmdstr += get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
532 /* second part (if present) will begin with a comma */
533 if (*cmdstr == ',') {
537 idx = get_address(cmdstr, &sed_cmd->end_line, &sed_cmd->end_match);
539 bb_error_msg_and_die("no address after comma");
543 /* skip whitespace before the command */
544 cmdstr = skip_whitespace(cmdstr);
546 /* Check for inversion flag */
547 if (*cmdstr == '!') {
551 /* skip whitespace before the command */
552 cmdstr = skip_whitespace(cmdstr);
555 /* last part (mandatory) will be a command */
557 bb_error_msg_and_die("missing command");
558 sed_cmd->cmd = *(cmdstr++);
559 cmdstr = parse_cmd_args(sed_cmd, cmdstr);
561 /* Add the command to the command array */
562 G.sed_cmd_tail->next = sed_cmd;
563 G.sed_cmd_tail = G.sed_cmd_tail->next;
566 /* If we glued multiple lines together, free the memory. */
567 free(G.add_cmd_line);
568 G.add_cmd_line = NULL;
571 /* Append to a string, reallocating memory as necessary. */
575 static void pipe_putc(char c)
577 if (G.pipeline.idx == G.pipeline.len) {
578 G.pipeline.buf = xrealloc(G.pipeline.buf,
579 G.pipeline.len + PIPE_GROW);
580 G.pipeline.len += PIPE_GROW;
582 G.pipeline.buf[G.pipeline.idx++] = c;
585 static void do_subst_w_backrefs(char *line, char *replace)
589 /* go through the replacement string */
590 for (i = 0; replace[i]; i++) {
591 /* if we find a backreference (\1, \2, etc.) print the backref'ed * text */
592 if (replace[i] == '\\') {
593 unsigned backref = replace[++i] - '0';
595 /* print out the text held in G.regmatch[backref] */
596 if (G.regmatch[backref].rm_so != -1) {
597 j = G.regmatch[backref].rm_so;
598 while (j < G.regmatch[backref].rm_eo)
599 pipe_putc(line[j++]);
603 /* I _think_ it is impossible to get '\' to be
604 * the last char in replace string. Thus we dont check
605 * for replace[i] == NUL. (counterexample anyone?) */
606 /* if we find a backslash escaped character, print the character */
607 pipe_putc(replace[i]);
610 /* if we find an unescaped '&' print out the whole matched text. */
611 if (replace[i] == '&') {
612 j = G.regmatch[0].rm_so;
613 while (j < G.regmatch[0].rm_eo)
614 pipe_putc(line[j++]);
617 /* Otherwise just output the character. */
618 pipe_putc(replace[i]);
622 static int do_subst_command(sed_cmd_t *sed_cmd, char **line)
624 char *oldline = *line;
627 regex_t *current_regex;
629 /* Handle empty regex. */
630 if (sed_cmd->sub_match == NULL) {
631 current_regex = G.previous_regex_ptr;
633 bb_error_msg_and_die("no previous regexp");
635 G.previous_regex_ptr = current_regex = sed_cmd->sub_match;
637 /* Find the first match */
638 if (REG_NOMATCH == regexec(current_regex, oldline, 10, G.regmatch, 0))
641 /* Initialize temporary output buffer. */
642 G.pipeline.buf = xmalloc(PIPE_GROW);
643 G.pipeline.len = PIPE_GROW;
646 /* Now loop through, substituting for matches */
650 /* Work around bug in glibc regexec, demonstrated by:
651 echo " a.b" | busybox sed 's [^ .]* x g'
652 The match_count check is so not to break
653 echo "hi" | busybox sed 's/^/!/g' */
654 if (!G.regmatch[0].rm_so && !G.regmatch[0].rm_eo && match_count) {
655 pipe_putc(*oldline++);
661 /* If we aren't interested in this match, output old line to
662 end of match and continue */
663 if (sed_cmd->which_match && sed_cmd->which_match != match_count) {
664 for (i = 0; i < G.regmatch[0].rm_eo; i++)
665 pipe_putc(*oldline++);
669 /* print everything before the match */
670 for (i = 0; i < G.regmatch[0].rm_so; i++)
671 pipe_putc(oldline[i]);
673 /* then print the substitution string */
674 do_subst_w_backrefs(oldline, sed_cmd->string);
676 /* advance past the match */
677 oldline += G.regmatch[0].rm_eo;
678 /* flag that something has changed */
681 /* if we're not doing this globally, get out now */
682 if (sed_cmd->which_match) break;
683 } while (*oldline && (regexec(current_regex, oldline, 10, G.regmatch, 0) != REG_NOMATCH));
685 /* Copy rest of string into output pipeline */
688 pipe_putc(*oldline++);
692 *line = G.pipeline.buf;
696 /* Set command pointer to point to this label. (Does not handle null label.) */
697 static sed_cmd_t *branch_to(char *label)
701 for (sed_cmd = G.sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
702 if (sed_cmd->cmd == ':' && sed_cmd->string && !strcmp(sed_cmd->string, label)) {
706 bb_error_msg_and_die("can't find label for jump to '%s'", label);
709 static void append(char *s)
711 llist_add_to_end(&G.append_head, xstrdup(s));
714 static void flush_append(void)
718 /* Output appended lines. */
719 while ((data = (char *)llist_pop(&G.append_head))) {
720 fprintf(G.nonstdout, "%s\n", data);
725 static void add_input_file(FILE *file)
727 G.input_file_list = xrealloc(G.input_file_list,
728 (G.input_file_count + 1) * sizeof(FILE *));
729 G.input_file_list[G.input_file_count++] = file;
732 /* Get next line of input from G.input_file_list, flushing append buffer and
733 * noting if we ran out of files without a newline on the last line we read.
739 static char *get_next_line(char *gets_char)
747 /* will be returned if last line in the file
748 * doesn't end with either '\n' or '\0' */
750 while (G.current_input_file < G.input_file_count) {
751 FILE *fp = G.input_file_list[G.current_input_file];
752 /* Read line up to a newline or NUL byte, inclusive,
753 * return malloc'ed char[]. length of the chunk read
754 * is stored in len. NULL if EOF/error */
755 temp = bb_get_chunk_from_file(fp, &len);
757 /* len > 0 here, it's ok to do temp[len-1] */
758 char c = temp[len-1];
759 if (c == '\n' || c == '\0') {
770 /* else we put NO_EOL_CHAR into *gets_char */
773 /* NB: I had the idea of peeking next file(s) and returning
774 * NO_EOL_CHAR only if it is the *last* non-empty
775 * input file. But there is a case where this won't work:
776 * file1: "a woo\nb woo"
777 * file2: "c no\nd no"
778 * sed -ne 's/woo/bang/p' input1 input2 => "a bang\nb bang"
779 * (note: *no* newline after "b bang"!) */
781 /* Close this file and advance to next one */
783 G.current_input_file++;
789 /* Output line of text. */
791 * The tricks with NO_EOL_CHAR and last_puts_char are there to emulate gnu sed.
792 * Without them, we had this:
796 * sed "s/i/z/" z1 z2 znull | hexdump -vC
799 * 00000000 74 68 7a 6e 67 79 0a 61 67 61 7a 6e |thzngy.agazn|
801 * 00000000 74 68 7a 6e 67 79 61 67 61 7a 6e |thzngyagazn|
803 static void puts_maybe_newline(char *s, FILE *file, char *last_puts_char, char last_gets_char)
805 char lpc = *last_puts_char;
807 /* Need to insert a '\n' between two files because first file's
808 * last line wasn't terminated? */
809 if (lpc != '\n' && lpc != '\0') {
815 /* 'x' - just something which is not '\n', '\0' or NO_EOL_CHAR */
819 /* had trailing '\0' and it was last char of file? */
820 if (last_gets_char == LAST_IS_NUL) {
824 /* had trailing '\n' or '\0'? */
825 if (last_gets_char != NO_EOL_CHAR) {
826 fputc(last_gets_char, file);
827 lpc = last_gets_char;
831 xfunc_error_retval = 4; /* It's what gnu sed exits with... */
832 bb_error_msg_and_die(bb_msg_write_error);
834 *last_puts_char = lpc;
837 #define sed_puts(s, n) (puts_maybe_newline(s, G.nonstdout, &last_puts_char, n))
839 static int beg_match(sed_cmd_t *sed_cmd, const char *pattern_space)
841 int retval = sed_cmd->beg_match && !regexec(sed_cmd->beg_match, pattern_space, 0, NULL, 0);
843 G.previous_regex_ptr = sed_cmd->beg_match;
847 /* Process all the lines in all the files */
849 static void process_files(void)
851 char *pattern_space, *next_line;
853 char last_puts_char = '\n';
854 char last_gets_char, next_gets_char;
859 next_line = get_next_line(&next_gets_char);
861 /* go through every line in each file */
865 /* Advance to next line. Stop if out of lines. */
866 pattern_space = next_line;
867 if (!pattern_space) return;
868 last_gets_char = next_gets_char;
870 /* Read one line in advance so we can act on the last line,
872 next_line = get_next_line(&next_gets_char);
875 /* for every line, go through all the commands */
876 for (sed_cmd = G.sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
877 int old_matched, matched;
879 old_matched = sed_cmd->in_match;
881 /* Determine if this command matches this line: */
883 /* Are we continuing a previous multi-line match? */
884 sed_cmd->in_match = sed_cmd->in_match
885 /* Or is no range necessary? */
886 || (!sed_cmd->beg_line && !sed_cmd->end_line
887 && !sed_cmd->beg_match && !sed_cmd->end_match)
888 /* Or did we match the start of a numerical range? */
889 || (sed_cmd->beg_line > 0 && (sed_cmd->beg_line == linenum))
890 /* Or does this line match our begin address regex? */
891 || (beg_match(sed_cmd, pattern_space))
892 /* Or did we match last line of input? */
893 || (sed_cmd->beg_line == -1 && next_line == NULL);
895 /* Snapshot the value */
897 matched = sed_cmd->in_match;
899 /* Is this line the end of the current match? */
902 sed_cmd->in_match = !(
903 /* has the ending line come, or is this a single address command? */
905 sed_cmd->end_line == -1 ?
907 : (sed_cmd->end_line <= linenum)
908 : !sed_cmd->end_match
910 /* or does this line matches our last address regex */
911 || (sed_cmd->end_match && old_matched
912 && (regexec(sed_cmd->end_match,
913 pattern_space, 0, NULL, 0) == 0))
917 /* Skip blocks of commands we didn't match. */
918 if (sed_cmd->cmd == '{') {
919 if (sed_cmd->invert ? matched : !matched) {
920 while (sed_cmd->cmd != '}') {
921 sed_cmd = sed_cmd->next;
923 bb_error_msg_and_die("unterminated {");
929 /* Okay, so did this line match? */
930 if (sed_cmd->invert ? !matched : matched) {
931 /* Update last used regex in case a blank substitute BRE is found */
932 if (sed_cmd->beg_match) {
933 G.previous_regex_ptr = sed_cmd->beg_match;
937 switch (sed_cmd->cmd) {
939 /* Print line number */
941 fprintf(G.nonstdout, "%d\n", linenum);
944 /* Write the current pattern space up to the first newline */
947 char *tmp = strchr(pattern_space, '\n');
951 /* TODO: explain why '\n' below */
952 sed_puts(pattern_space, '\n');
959 /* Write the current pattern space to output */
961 /* NB: we print this _before_ the last line
962 * (of current file) is printed. Even if
963 * that line is nonterminated, we print
964 * '\n' here (gnu sed does the same) */
965 sed_puts(pattern_space, '\n');
967 /* Delete up through first newline */
970 char *tmp = strchr(pattern_space, '\n');
973 tmp = xstrdup(tmp+1);
979 /* discard this line. */
983 /* Substitute with regex */
985 if (!do_subst_command(sed_cmd, &pattern_space))
989 /* handle p option */
991 sed_puts(pattern_space, last_gets_char);
992 /* handle w option */
993 if (sed_cmd->sw_file)
995 pattern_space, sed_cmd->sw_file,
996 &sed_cmd->sw_last_char, last_gets_char);
999 /* Append line to linked list to be printed later */
1001 append(sed_cmd->string);
1004 /* Insert text before this line */
1006 sed_puts(sed_cmd->string, '\n');
1009 /* Cut and paste text (replace) */
1011 /* Only triggers on last line of a matching range. */
1012 if (!sed_cmd->in_match)
1013 sed_puts(sed_cmd->string, NO_EOL_CHAR);
1016 /* Read file, append contents to output */
1021 rfile = fopen(sed_cmd->string, "r");
1025 while ((line = xmalloc_getline(rfile))
1028 xprint_and_close_file(rfile);
1034 /* Write pattern space to file. */
1037 pattern_space, sed_cmd->sw_file,
1038 &sed_cmd->sw_last_char, last_gets_char);
1041 /* Read next line from input */
1044 sed_puts(pattern_space, last_gets_char);
1046 free(pattern_space);
1047 pattern_space = next_line;
1048 last_gets_char = next_gets_char;
1049 next_line = get_next_line(&next_gets_char);
1055 /* Quit. End of script, end of input. */
1057 /* Exit the outer while loop */
1060 goto discard_commands;
1062 /* Append the next line to the current line */
1066 /* If no next line, jump to end of script and exit. */
1067 if (next_line == NULL) {
1068 /* Jump to end of script and exit */
1072 /* append next_line, read new next_line. */
1074 len = strlen(pattern_space);
1075 pattern_space = realloc(pattern_space, len + strlen(next_line) + 2);
1076 pattern_space[len] = '\n';
1077 strcpy(pattern_space + len+1, next_line);
1078 last_gets_char = next_gets_char;
1079 next_line = get_next_line(&next_gets_char);
1084 /* Test/branch if substitution occurred */
1086 if (!substituted) break;
1089 /* Test/branch if substitution didn't occur */
1091 if (substituted) break;
1093 /* Branch to label */
1095 if (!sed_cmd->string) goto discard_commands;
1096 else sed_cmd = branch_to(sed_cmd->string);
1098 /* Transliterate characters */
1103 for (i = 0; pattern_space[i]; i++) {
1104 for (j = 0; sed_cmd->string[j]; j += 2) {
1105 if (pattern_space[i] == sed_cmd->string[j]) {
1106 pattern_space[i] = sed_cmd->string[j + 1];
1114 case 'g': /* Replace pattern space with hold space */
1115 free(pattern_space);
1116 pattern_space = xstrdup(G.hold_space ? G.hold_space : "");
1118 case 'G': /* Append newline and hold space to pattern space */
1120 int pattern_space_size = 2;
1121 int hold_space_size = 0;
1124 pattern_space_size += strlen(pattern_space);
1126 hold_space_size = strlen(G.hold_space);
1127 pattern_space = xrealloc(pattern_space,
1128 pattern_space_size + hold_space_size);
1129 if (pattern_space_size == 2)
1130 pattern_space[0] = 0;
1131 strcat(pattern_space, "\n");
1133 strcat(pattern_space, G.hold_space);
1134 last_gets_char = '\n';
1138 case 'h': /* Replace hold space with pattern space */
1140 G.hold_space = xstrdup(pattern_space);
1142 case 'H': /* Append newline and pattern space to hold space */
1144 int hold_space_size = 2;
1145 int pattern_space_size = 0;
1148 hold_space_size += strlen(G.hold_space);
1150 pattern_space_size = strlen(pattern_space);
1151 G.hold_space = xrealloc(G.hold_space,
1152 hold_space_size + pattern_space_size);
1154 if (hold_space_size == 2)
1156 strcat(G.hold_space, "\n");
1158 strcat(G.hold_space, pattern_space);
1162 case 'x': /* Exchange hold and pattern space */
1164 char *tmp = pattern_space;
1165 pattern_space = G.hold_space ? : xzalloc(1);
1166 last_gets_char = '\n';
1175 * exit point from sedding...
1178 /* we will print the line unless we were told to be quiet ('-n')
1179 or if the line was suppressed (ala 'd'elete) */
1181 sed_puts(pattern_space, last_gets_char);
1183 /* Delete and such jump here. */
1186 free(pattern_space);
1191 /* It is possible to have a command line argument with embedded
1192 * newlines. This counts as multiple command lines.
1193 * However, newline can be escaped: 's/e/z\<newline>z/'
1194 * We check for this.
1197 static void add_cmd_block(char *cmdstr)
1201 cmdstr = sv = xstrdup(cmdstr);
1203 eol = strchr(cmdstr, '\n');
1206 /* Count preceding slashes */
1210 while (sl != cmdstr && *--sl == '\\')
1212 /* Odd number of preceding slashes - newline is escaped */
1215 eol = strchr(eol, '\n');
1226 int sed_main(int argc, char **argv);
1227 int sed_main(int argc, char **argv)
1230 OPT_in_place = 1 << 0,
1233 llist_t *opt_e, *opt_f;
1234 int status = EXIT_SUCCESS;
1238 /* destroy command strings on exit */
1239 if (ENABLE_FEATURE_CLEAN_UP) atexit(sed_free_and_close_stuff);
1241 /* Lie to autoconf when it starts asking stupid questions. */
1242 if (argc == 2 && !strcmp(argv[1], "--version")) {
1243 puts("This is not GNU sed version 4.0");
1247 /* do normal option parsing */
1248 opt_e = opt_f = NULL;
1249 opt_complementary = "e::f::" /* can occur multiple times */
1250 "nn"; /* count -n */
1251 opt = getopt32(argv, "irne:f:", &opt_e, &opt_f,
1252 &G.be_quiet); /* counter for -n */
1255 if (opt & OPT_in_place) { // -i
1256 atexit(cleanup_outname);
1258 if (opt & 0x2) G.regex_type |= REG_EXTENDED; // -r
1259 //if (opt & 0x4) G.be_quiet++; // -n
1260 while (opt_e) { // -e
1261 add_cmd_block(opt_e->data);
1262 opt_e = opt_e->link;
1263 /* we leak opt_e here... */
1265 while (opt_f) { // -f
1268 cmdfile = xfopen(opt_f->data, "r");
1269 while ((line = xmalloc_getline(cmdfile)) != NULL) {
1274 opt_f = opt_f->link;
1275 /* we leak opt_f here... */
1277 /* if we didn't get a pattern from -e or -f, use argv[0] */
1278 if (!(opt & 0x18)) {
1281 add_cmd_block(*argv++);
1284 /* Flush any unfinished commands. */
1287 /* By default, we write to stdout */
1288 G.nonstdout = stdout;
1290 /* argv[0..(argc-1)] should be names of file to process. If no
1291 * files were specified or '-' was specified, take input from stdin.
1292 * Otherwise, we process all the files specified. */
1293 if (argv[0] == NULL) {
1294 if (opt & OPT_in_place)
1295 bb_error_msg_and_die(bb_msg_requires_arg, "-i");
1296 add_input_file(stdin);
1302 for (i = 0; i < argc; i++) {
1303 struct stat statbuf;
1306 if (LONE_DASH(argv[i]) && !(opt & OPT_in_place)) {
1307 add_input_file(stdin);
1311 file = fopen_or_warn(argv[i], "r");
1313 status = EXIT_FAILURE;
1316 if (!(opt & OPT_in_place)) {
1317 add_input_file(file);
1321 G.outname = xasprintf("%sXXXXXX", argv[i]);
1322 nonstdoutfd = mkstemp(G.outname);
1323 if (-1 == nonstdoutfd)
1324 bb_perror_msg_and_die("cannot create temp file %s", G.outname);
1325 G.nonstdout = fdopen(nonstdoutfd, "w");
1327 /* Set permissions of output file */
1329 fstat(fileno(file), &statbuf);
1330 fchmod(nonstdoutfd, statbuf.st_mode);
1331 add_input_file(file);
1333 fclose(G.nonstdout);
1335 G.nonstdout = stdout;
1336 /* unlink(argv[i]); */
1337 // FIXME: error check / message?
1338 rename(G.outname, argv[i]);
1342 if (G.input_file_count > G.current_input_file)