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
9 * Copyright (C) 2003,2004 by Rob Landley <rob@landley.net>
11 * MAINTAINER: Rob Landley <rob@landley.net>
13 * Licensed under GPLv2, see file LICENSE in this source tree.
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.
36 /* Supported features and commands in this version of sed:
39 * - address matching: num|/matchstr/[,num|/matchstr/|$]command
40 * - commands: (p)rint, (d)elete, (s)ubstitue (with g & I flags)
41 * - edit commands: (a)ppend, (i)nsert, (c)hange
42 * - file commands: (r)ead
43 * - backreferences in substitution expressions (\0, \1, \2...\9)
44 * - grouped commands: {cmd1;cmd2}
45 * - transliteration (y/source-chars/dest-chars/)
46 * - pattern space hold space storing / swapping (g, h, x)
47 * - labels / branching (: label, b, t, T)
49 * (Note: Specifying an address (range) to match is *optional*; commands
50 * default to the whole pattern space if no specific address match was
54 * - Create a wrapper around regex to make libc's regex conform with sed
56 * Reference http://www.opengroup.org/onlinepubs/007904975/utilities/sed.html
59 //usage:#define sed_trivial_usage
60 //usage: "[-efinr] SED_CMD [FILE]..."
61 //usage:#define sed_full_usage "\n\n"
62 //usage: " -e CMD Add CMD to sed commands to be executed"
63 //usage: "\n -f FILE Add FILE contents to sed commands to be executed"
64 //usage: "\n -i Edit files in-place (else sends result to stdout)"
65 //usage: "\n -n Suppress automatic printing of pattern space"
66 //usage: "\n -r Use extended regex syntax"
68 //usage: "\nIf no -e or -f, the first non-option argument is the sed command string."
69 //usage: "\nRemaining arguments are input files (stdin if none)."
71 //usage:#define sed_example_usage
72 //usage: "$ echo \"foo\" | sed -e 's/f[a-zA-Z]o/bar/g'\n"
79 OPT_in_place = 1 << 0,
82 /* Each sed command turns into one of these structures. */
83 typedef struct sed_cmd_s {
84 /* Ordered by alignment requirements: currently 36 bytes on x86 */
85 struct sed_cmd_s *next; /* Next command (linked list, NULL terminated) */
88 regex_t *beg_match; /* sed -e '/match/cmd' */
89 regex_t *end_match; /* sed -e '/match/,/end_match/cmd' */
90 regex_t *sub_match; /* For 's/sub_match/string/' */
91 int beg_line; /* 'sed 1p' 0 == apply commands to all lines */
92 int end_line; /* 'sed 1,3p' 0 == one line only. -1 = last line ($) */
94 FILE *sw_file; /* File (sw) command writes to, -1 for none. */
95 char *string; /* Data string for (saicytb) commands. */
97 unsigned which_match; /* (s) Which match to replace (0 for all) */
99 /* Bitfields (gcc won't group them if we don't) */
100 unsigned invert:1; /* the '!' after the address */
101 unsigned in_match:1; /* Next line also included in match? */
102 unsigned sub_p:1; /* (s) print option */
104 char sw_last_char; /* Last line written by (sw) had no '\n' */
107 char cmd; /* The command char: abcdDgGhHilnNpPqrstwxy:={} */
110 static const char semicolon_whitespace[] ALIGN1 = "; \n\r\t\v";
114 int be_quiet, regex_type;
116 char *outname, *hold_space;
118 /* List of input files */
119 int input_file_count, current_input_file;
120 FILE **input_file_list;
122 regmatch_t regmatch[10];
123 regex_t *previous_regex_ptr;
125 /* linked list of sed commands */
126 sed_cmd_t sed_cmd_head, *sed_cmd_tail;
128 /* Linked list of append lines */
129 llist_t *append_head;
134 char *buf; /* Space to hold string */
135 int idx; /* Space used */
136 int len; /* Space allocated */
139 #define G (*(struct globals*)&bb_common_bufsiz1)
140 struct BUG_G_too_big {
141 char BUG_G_too_big[sizeof(G) <= COMMON_BUFSIZE ? 1 : -1];
143 #define INIT_G() do { \
144 G.sed_cmd_tail = &G.sed_cmd_head; \
148 #if ENABLE_FEATURE_CLEAN_UP
149 static void sed_free_and_close_stuff(void)
151 sed_cmd_t *sed_cmd = G.sed_cmd_head.next;
153 llist_free(G.append_head, free);
156 sed_cmd_t *sed_cmd_next = sed_cmd->next;
158 if (sed_cmd->sw_file)
159 xprint_and_close_file(sed_cmd->sw_file);
161 if (sed_cmd->beg_match) {
162 regfree(sed_cmd->beg_match);
163 free(sed_cmd->beg_match);
165 if (sed_cmd->end_match) {
166 regfree(sed_cmd->end_match);
167 free(sed_cmd->end_match);
169 if (sed_cmd->sub_match) {
170 regfree(sed_cmd->sub_match);
171 free(sed_cmd->sub_match);
173 free(sed_cmd->string);
175 sed_cmd = sed_cmd_next;
180 while (G.current_input_file < G.input_file_count)
181 fclose(G.input_file_list[G.current_input_file++]);
184 void sed_free_and_close_stuff(void);
187 /* If something bad happens during -i operation, delete temp file */
189 static void cleanup_outname(void)
191 if (G.outname) unlink(G.outname);
194 /* strcpy, replacing "\from" with 'to'. If to is NUL, replacing "\any" with 'any' */
196 static void parse_escapes(char *dest, const char *string, int len, char from, char to)
201 if (string[i] == '\\') {
202 if (!to || string[i+1] == from) {
203 *dest++ = to ? to : string[i+1];
207 *dest++ = string[i++];
209 /* TODO: is it safe wrt a string with trailing '\\' ? */
210 *dest++ = string[i++];
215 static char *copy_parsing_escapes(const char *string, int len)
218 char *dest = xmalloc(len + 1);
220 /* sed recognizes \n */
221 /* GNU sed also recognizes \t and \r */
222 for (s = "\nn\tt\rr"; *s; s += 2) {
223 parse_escapes(dest, string, len, s[1], s[0]);
232 * index_of_next_unescaped_regexp_delim - walks left to right through a string
233 * beginning at a specified index and returns the index of the next regular
234 * expression delimiter (typically a forward slash ('/')) not preceded by
235 * a backslash ('\'). A negative delimiter disables square bracket checking.
237 static int index_of_next_unescaped_regexp_delim(int delimiter, const char *str)
246 delimiter = -delimiter;
249 for (; (ch = str[idx]) != '\0'; idx++) {
252 && !(bracket == idx - 1 || (bracket == idx - 2 && str[idx - 1] == '^'))
260 else if (bracket == -1 && ch == '[')
262 else if (ch == delimiter)
266 /* if we make it to here, we've hit the end of the string */
267 bb_error_msg_and_die("unmatched '%c'", delimiter);
271 * Returns the index of the third delimiter
273 static int parse_regex_delim(const char *cmdstr, char **match, char **replace)
275 const char *cmdstr_ptr = cmdstr;
279 /* verify that the 's' or 'y' is followed by something. That something
280 * (typically a 'slash') is now our regexp delimiter... */
282 bb_error_msg_and_die("bad format in substitution expression");
283 delimiter = *cmdstr_ptr++;
285 /* save the match string */
286 idx = index_of_next_unescaped_regexp_delim(delimiter, cmdstr_ptr);
287 *match = copy_parsing_escapes(cmdstr_ptr, idx);
289 /* save the replacement string */
290 cmdstr_ptr += idx + 1;
291 idx = index_of_next_unescaped_regexp_delim(-delimiter, cmdstr_ptr);
292 *replace = copy_parsing_escapes(cmdstr_ptr, idx);
294 return ((cmdstr_ptr - cmdstr) + idx);
298 * returns the index in the string just past where the address ends.
300 static int get_address(const char *my_str, int *linenum, regex_t ** regex)
302 const char *pos = my_str;
304 if (isdigit(*my_str)) {
305 *linenum = strtol(my_str, (char**)&pos, 10);
306 /* endstr shouldnt ever equal NULL */
307 } else if (*my_str == '$') {
310 } else if (*my_str == '/' || *my_str == '\\') {
316 if (*my_str == '\\') delimiter = *++pos;
317 next = index_of_next_unescaped_regexp_delim(delimiter, ++pos);
318 temp = copy_parsing_escapes(pos, next);
319 *regex = xmalloc(sizeof(regex_t));
320 xregcomp(*regex, temp, G.regex_type|REG_NEWLINE);
322 /* Move position to next character after last delimiter */
328 /* Grab a filename. Whitespace at start is skipped, then goes to EOL. */
329 static int parse_file_cmd(/*sed_cmd_t *sed_cmd,*/ const char *filecmdstr, char **retval)
331 int start = 0, idx, hack = 0;
333 /* Skip whitespace, then grab filename to end of line */
334 while (isspace(filecmdstr[start]))
337 while (filecmdstr[idx] && filecmdstr[idx] != '\n')
340 /* If lines glued together, put backslash back. */
341 if (filecmdstr[idx] == '\n')
344 bb_error_msg_and_die("empty filename");
345 *retval = xstrndup(filecmdstr+start, idx-start+hack+1);
347 (*retval)[idx] = '\\';
352 static int parse_subst_cmd(sed_cmd_t *sed_cmd, const char *substr)
354 int cflags = G.regex_type;
359 * A substitution command should look something like this:
360 * s/match/replace/ #gIpw
364 idx = parse_regex_delim(substr, &match, &sed_cmd->string);
366 /* determine the number of back references in the match string */
367 /* Note: we compute this here rather than in the do_subst_command()
368 * function to save processor time, at the expense of a little more memory
369 * (4 bits) per sed_cmd */
371 /* process the flags */
373 sed_cmd->which_match = 1;
374 while (substr[++idx]) {
375 /* Parse match number */
376 if (isdigit(substr[idx])) {
377 if (match[0] != '^') {
378 /* Match 0 treated as all, multiple matches we take the last one. */
379 const char *pos = substr + idx;
380 /* FIXME: error check? */
381 sed_cmd->which_match = (unsigned)strtol(substr+idx, (char**) &pos, 10);
387 if (isspace(substr[idx]))
390 switch (substr[idx]) {
391 /* Replace all occurrences */
394 sed_cmd->which_match = 0;
396 /* Print pattern space */
404 idx += parse_file_cmd(/*sed_cmd,*/ substr+idx, &temp);
407 /* Ignore case (gnu exension) */
413 // while (substr[++idx]) continue;
414 idx += strlen(substr + idx); // same
421 bb_error_msg_and_die("bad option in substitution expression");
425 /* compile the match string into a regex */
426 if (*match != '\0') {
427 /* If match is empty, we use last regex used at runtime */
428 sed_cmd->sub_match = xmalloc(sizeof(regex_t));
429 xregcomp(sed_cmd->sub_match, match, cflags);
437 * Process the commands arguments
439 static const char *parse_cmd_args(sed_cmd_t *sed_cmd, const char *cmdstr)
441 static const char cmd_letters[] = "saicrw:btTydDgGhHlnNpPqx={}";
472 struct chk { char chk[sizeof(cmd_letters)-1 == IDX_nul ? 1 : -1]; };
474 unsigned idx = strchrnul(cmd_letters, sed_cmd->cmd) - cmd_letters;
476 /* handle (s)ubstitution command */
478 cmdstr += parse_subst_cmd(sed_cmd, cmdstr);
480 /* handle edit cmds: (a)ppend, (i)nsert, and (c)hange */
481 else if (idx <= IDX_c) { /* a,i,c */
482 if ((sed_cmd->end_line || sed_cmd->end_match) && sed_cmd->cmd != 'c')
483 bb_error_msg_and_die("only a beginning address can be specified for edit commands");
485 if (*cmdstr == '\n' || *cmdstr == '\\') {
489 if (!isspace(*cmdstr))
493 sed_cmd->string = xstrdup(cmdstr);
494 /* "\anychar" -> "anychar" */
495 parse_escapes(sed_cmd->string, sed_cmd->string, strlen(cmdstr), '\0', '\0');
496 cmdstr += strlen(cmdstr);
498 /* handle file cmds: (r)ead */
499 else if (idx <= IDX_w) { /* r,w */
500 if (sed_cmd->end_line || sed_cmd->end_match)
501 bb_error_msg_and_die("command only uses one address");
502 cmdstr += parse_file_cmd(/*sed_cmd,*/ cmdstr, &sed_cmd->string);
503 if (sed_cmd->cmd == 'w') {
504 sed_cmd->sw_file = xfopen_for_write(sed_cmd->string);
505 sed_cmd->sw_last_char = '\n';
508 /* handle branch commands */
509 else if (idx <= IDX_T) { /* :,b,t,T */
512 cmdstr = skip_whitespace(cmdstr);
513 length = strcspn(cmdstr, semicolon_whitespace);
515 sed_cmd->string = xstrndup(cmdstr, length);
519 /* translation command */
520 else if (idx == IDX_y) {
521 char *match, *replace;
524 cmdstr += parse_regex_delim(cmdstr, &match, &replace)+1;
525 /* \n already parsed, but \delimiter needs unescaping. */
526 parse_escapes(match, match, strlen(match), i, i);
527 parse_escapes(replace, replace, strlen(replace), i, i);
529 sed_cmd->string = xzalloc((strlen(match) + 1) * 2);
530 for (i = 0; match[i] && replace[i]; i++) {
531 sed_cmd->string[i*2] = match[i];
532 sed_cmd->string[i*2+1] = replace[i];
537 /* if it wasnt a single-letter command that takes no arguments
538 * then it must be an invalid command.
540 else if (idx >= IDX_nul) { /* not d,D,g,G,h,H,l,n,N,p,P,q,x,=,{,} */
541 bb_error_msg_and_die("unsupported command %c", sed_cmd->cmd);
544 /* give back whatever's left over */
549 /* Parse address+command sets, skipping comment lines. */
551 static void add_cmd(const char *cmdstr)
556 /* Append this line to any unfinished line from last time. */
557 if (G.add_cmd_line) {
558 char *tp = xasprintf("%s\n%s", G.add_cmd_line, cmdstr);
559 free(G.add_cmd_line);
560 cmdstr = G.add_cmd_line = tp;
563 /* If this line ends with unescaped backslash, request next line. */
564 n = len = strlen(cmdstr);
565 while (n && cmdstr[n-1] == '\\')
567 if ((len - n) & 1) { /* if odd number of trailing backslashes */
569 G.add_cmd_line = xstrdup(cmdstr);
570 G.add_cmd_line[len-1] = '\0';
574 /* Loop parsing all commands in this line. */
576 /* Skip leading whitespace and semicolons */
577 cmdstr += strspn(cmdstr, semicolon_whitespace);
579 /* If no more commands, exit. */
582 /* if this is a comment, jump past it and keep going */
583 if (*cmdstr == '#') {
584 /* "#n" is the same as using -n on the command line */
585 if (cmdstr[1] == 'n')
587 cmdstr = strpbrk(cmdstr, "\n\r");
593 * format is: [addr][,addr][!]cmd
598 sed_cmd = xzalloc(sizeof(sed_cmd_t));
600 /* first part (if present) is an address: either a '$', a number or a /regex/ */
601 cmdstr += get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
603 /* second part (if present) will begin with a comma */
604 if (*cmdstr == ',') {
608 idx = get_address(cmdstr, &sed_cmd->end_line, &sed_cmd->end_match);
610 bb_error_msg_and_die("no address after comma");
614 /* skip whitespace before the command */
615 cmdstr = skip_whitespace(cmdstr);
617 /* Check for inversion flag */
618 if (*cmdstr == '!') {
622 /* skip whitespace before the command */
623 cmdstr = skip_whitespace(cmdstr);
626 /* last part (mandatory) will be a command */
628 bb_error_msg_and_die("missing command");
629 sed_cmd->cmd = *cmdstr++;
630 cmdstr = parse_cmd_args(sed_cmd, cmdstr);
632 /* Add the command to the command array */
633 G.sed_cmd_tail->next = sed_cmd;
634 G.sed_cmd_tail = G.sed_cmd_tail->next;
637 /* If we glued multiple lines together, free the memory. */
638 free(G.add_cmd_line);
639 G.add_cmd_line = NULL;
642 /* Append to a string, reallocating memory as necessary. */
646 static void pipe_putc(char c)
648 if (G.pipeline.idx == G.pipeline.len) {
649 G.pipeline.buf = xrealloc(G.pipeline.buf,
650 G.pipeline.len + PIPE_GROW);
651 G.pipeline.len += PIPE_GROW;
653 G.pipeline.buf[G.pipeline.idx++] = c;
656 static void do_subst_w_backrefs(char *line, char *replace)
660 /* go through the replacement string */
661 for (i = 0; replace[i]; i++) {
662 /* if we find a backreference (\1, \2, etc.) print the backref'ed * text */
663 if (replace[i] == '\\') {
664 unsigned backref = replace[++i] - '0';
666 /* print out the text held in G.regmatch[backref] */
667 if (G.regmatch[backref].rm_so != -1) {
668 j = G.regmatch[backref].rm_so;
669 while (j < G.regmatch[backref].rm_eo)
670 pipe_putc(line[j++]);
674 /* I _think_ it is impossible to get '\' to be
675 * the last char in replace string. Thus we dont check
676 * for replace[i] == NUL. (counterexample anyone?) */
677 /* if we find a backslash escaped character, print the character */
678 pipe_putc(replace[i]);
681 /* if we find an unescaped '&' print out the whole matched text. */
682 if (replace[i] == '&') {
683 j = G.regmatch[0].rm_so;
684 while (j < G.regmatch[0].rm_eo)
685 pipe_putc(line[j++]);
688 /* Otherwise just output the character. */
689 pipe_putc(replace[i]);
693 static int do_subst_command(sed_cmd_t *sed_cmd, char **line_p)
695 char *line = *line_p;
697 unsigned match_count = 0;
698 regex_t *current_regex;
700 current_regex = sed_cmd->sub_match;
701 /* Handle empty regex. */
702 if (!current_regex) {
703 current_regex = G.previous_regex_ptr;
705 bb_error_msg_and_die("no previous regexp");
707 G.previous_regex_ptr = current_regex;
709 /* Find the first match */
710 if (REG_NOMATCH == regexec(current_regex, line, 10, G.regmatch, 0))
713 /* Initialize temporary output buffer. */
714 G.pipeline.buf = xmalloc(PIPE_GROW);
715 G.pipeline.len = PIPE_GROW;
718 /* Now loop through, substituting for matches */
722 /* Work around bug in glibc regexec, demonstrated by:
723 echo " a.b" | busybox sed 's [^ .]* x g'
724 The match_count check is so not to break
725 echo "hi" | busybox sed 's/^/!/g' */
726 if (!G.regmatch[0].rm_so && !G.regmatch[0].rm_eo && match_count) {
733 /* If we aren't interested in this match, output old line to
734 end of match and continue */
735 if (sed_cmd->which_match
736 && (sed_cmd->which_match != match_count)
738 for (i = 0; i < G.regmatch[0].rm_eo; i++)
743 /* print everything before the match */
744 for (i = 0; i < G.regmatch[0].rm_so; i++)
747 /* then print the substitution string */
748 do_subst_w_backrefs(line, sed_cmd->string);
750 /* advance past the match */
751 line += G.regmatch[0].rm_eo;
752 /* flag that something has changed */
755 /* if we're not doing this globally, get out now */
756 if (sed_cmd->which_match)
759 //maybe (G.regmatch[0].rm_eo ? REG_NOTBOL : 0) instead of unconditional REG_NOTBOL?
760 } while (*line && regexec(current_regex, line, 10, G.regmatch, REG_NOTBOL) != REG_NOMATCH);
762 /* Copy rest of string into output pipeline */
771 *line_p = G.pipeline.buf;
775 /* Set command pointer to point to this label. (Does not handle null label.) */
776 static sed_cmd_t *branch_to(char *label)
780 for (sed_cmd = G.sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
781 if (sed_cmd->cmd == ':' && sed_cmd->string && !strcmp(sed_cmd->string, label)) {
785 bb_error_msg_and_die("can't find label for jump to '%s'", label);
788 static void append(char *s)
790 llist_add_to_end(&G.append_head, xstrdup(s));
793 static void flush_append(void)
797 /* Output appended lines. */
798 while ((data = (char *)llist_pop(&G.append_head))) {
799 fprintf(G.nonstdout, "%s\n", data);
804 static void add_input_file(FILE *file)
806 G.input_file_list = xrealloc_vector(G.input_file_list, 2, G.input_file_count);
807 G.input_file_list[G.input_file_count++] = file;
810 /* Get next line of input from G.input_file_list, flushing append buffer and
811 * noting if we ran out of files without a newline on the last line we read.
817 static char *get_next_line(char *gets_char)
825 /* will be returned if last line in the file
826 * doesn't end with either '\n' or '\0' */
828 while (G.current_input_file < G.input_file_count) {
829 FILE *fp = G.input_file_list[G.current_input_file];
830 /* Read line up to a newline or NUL byte, inclusive,
831 * return malloc'ed char[]. length of the chunk read
832 * is stored in len. NULL if EOF/error */
833 temp = bb_get_chunk_from_file(fp, &len);
835 /* len > 0 here, it's ok to do temp[len-1] */
836 char c = temp[len-1];
837 if (c == '\n' || c == '\0') {
848 /* else we put NO_EOL_CHAR into *gets_char */
851 /* NB: I had the idea of peeking next file(s) and returning
852 * NO_EOL_CHAR only if it is the *last* non-empty
853 * input file. But there is a case where this won't work:
854 * file1: "a woo\nb woo"
855 * file2: "c no\nd no"
856 * sed -ne 's/woo/bang/p' input1 input2 => "a bang\nb bang"
857 * (note: *no* newline after "b bang"!) */
859 /* Close this file and advance to next one */
861 G.current_input_file++;
867 /* Output line of text. */
869 * The tricks with NO_EOL_CHAR and last_puts_char are there to emulate gnu sed.
870 * Without them, we had this:
874 * sed "s/i/z/" z1 z2 znull | hexdump -vC
877 * 00000000 74 68 7a 6e 67 79 0a 61 67 61 7a 6e |thzngy.agazn|
879 * 00000000 74 68 7a 6e 67 79 61 67 61 7a 6e |thzngyagazn|
881 static void puts_maybe_newline(char *s, FILE *file, char *last_puts_char, char last_gets_char)
883 char lpc = *last_puts_char;
885 /* Need to insert a '\n' between two files because first file's
886 * last line wasn't terminated? */
887 if (lpc != '\n' && lpc != '\0') {
893 /* 'x' - just something which is not '\n', '\0' or NO_EOL_CHAR */
897 /* had trailing '\0' and it was last char of file? */
898 if (last_gets_char == LAST_IS_NUL) {
902 /* had trailing '\n' or '\0'? */
903 if (last_gets_char != NO_EOL_CHAR) {
904 fputc(last_gets_char, file);
905 lpc = last_gets_char;
909 xfunc_error_retval = 4; /* It's what gnu sed exits with... */
910 bb_error_msg_and_die(bb_msg_write_error);
912 *last_puts_char = lpc;
915 #define sed_puts(s, n) (puts_maybe_newline(s, G.nonstdout, &last_puts_char, n))
917 static int beg_match(sed_cmd_t *sed_cmd, const char *pattern_space)
919 int retval = sed_cmd->beg_match && !regexec(sed_cmd->beg_match, pattern_space, 0, NULL, 0);
921 G.previous_regex_ptr = sed_cmd->beg_match;
925 /* Process all the lines in all the files */
927 static void process_files(void)
929 char *pattern_space, *next_line;
931 char last_puts_char = '\n';
932 char last_gets_char, next_gets_char;
937 next_line = get_next_line(&next_gets_char);
939 /* Go through every line in each file */
943 /* Advance to next line. Stop if out of lines. */
944 pattern_space = next_line;
947 last_gets_char = next_gets_char;
949 /* Read one line in advance so we can act on the last line,
951 next_line = get_next_line(&next_gets_char);
954 /* For every line, go through all the commands */
956 for (sed_cmd = G.sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
957 int old_matched, matched;
959 old_matched = sed_cmd->in_match;
961 /* Determine if this command matches this line: */
963 //bb_error_msg("match1:%d", sed_cmd->in_match);
964 //bb_error_msg("match2:%d", (!sed_cmd->beg_line && !sed_cmd->end_line
965 // && !sed_cmd->beg_match && !sed_cmd->end_match));
966 //bb_error_msg("match3:%d", (sed_cmd->beg_line > 0
967 // && (sed_cmd->end_line || sed_cmd->end_match
968 // ? (sed_cmd->beg_line <= linenum)
969 // : (sed_cmd->beg_line == linenum)
972 //bb_error_msg("match4:%d", (beg_match(sed_cmd, pattern_space)));
973 //bb_error_msg("match5:%d", (sed_cmd->beg_line == -1 && next_line == NULL));
975 /* Are we continuing a previous multi-line match? */
976 sed_cmd->in_match = sed_cmd->in_match
977 /* Or is no range necessary? */
978 || (!sed_cmd->beg_line && !sed_cmd->end_line
979 && !sed_cmd->beg_match && !sed_cmd->end_match)
980 /* Or did we match the start of a numerical range? */
981 || (sed_cmd->beg_line > 0
982 && (sed_cmd->end_line || sed_cmd->end_match
983 /* note: even if end is numeric and is < linenum too,
984 * GNU sed matches! We match too */
985 ? (sed_cmd->beg_line <= linenum) /* N,end */
986 : (sed_cmd->beg_line == linenum) /* N */
989 /* Or does this line match our begin address regex? */
990 || (beg_match(sed_cmd, pattern_space))
991 /* Or did we match last line of input? */
992 || (sed_cmd->beg_line == -1 && next_line == NULL);
994 /* Snapshot the value */
995 matched = sed_cmd->in_match;
997 //bb_error_msg("cmd:'%c' matched:%d beg_line:%d end_line:%d linenum:%d",
998 //sed_cmd->cmd, matched, sed_cmd->beg_line, sed_cmd->end_line, linenum);
1000 /* Is this line the end of the current match? */
1003 /* once matched, "n,xxx" range is dead, disabling it */
1004 if (sed_cmd->beg_line > 0
1005 && !(option_mask32 & OPT_in_place) /* but not for -i */
1007 sed_cmd->beg_line = -2;
1009 sed_cmd->in_match = !(
1010 /* has the ending line come, or is this a single address command? */
1012 ? sed_cmd->end_line == -1
1014 : (sed_cmd->end_line <= linenum)
1015 : !sed_cmd->end_match
1017 /* or does this line matches our last address regex */
1018 || (sed_cmd->end_match && old_matched
1019 && (regexec(sed_cmd->end_match,
1020 pattern_space, 0, NULL, 0) == 0))
1024 /* Skip blocks of commands we didn't match */
1025 if (sed_cmd->cmd == '{') {
1026 if (sed_cmd->invert ? matched : !matched) {
1027 unsigned nest_cnt = 0;
1029 if (sed_cmd->cmd == '{')
1031 if (sed_cmd->cmd == '}') {
1036 sed_cmd = sed_cmd->next;
1038 bb_error_msg_and_die("unterminated {");
1044 /* Okay, so did this line match? */
1045 if (sed_cmd->invert ? matched : !matched)
1048 /* Update last used regex in case a blank substitute BRE is found */
1049 if (sed_cmd->beg_match) {
1050 G.previous_regex_ptr = sed_cmd->beg_match;
1053 /* actual sedding */
1054 //bb_error_msg("pattern_space:'%s' next_line:'%s' cmd:%c",
1055 //pattern_space, next_line, sed_cmd->cmd);
1056 switch (sed_cmd->cmd) {
1058 /* Print line number */
1060 fprintf(G.nonstdout, "%d\n", linenum);
1063 /* Write the current pattern space up to the first newline */
1066 char *tmp = strchr(pattern_space, '\n');
1069 /* TODO: explain why '\n' below */
1070 sed_puts(pattern_space, '\n');
1077 /* Write the current pattern space to output */
1079 /* NB: we print this _before_ the last line
1080 * (of current file) is printed. Even if
1081 * that line is nonterminated, we print
1082 * '\n' here (gnu sed does the same) */
1083 sed_puts(pattern_space, '\n');
1085 /* Delete up through first newline */
1088 char *tmp = strchr(pattern_space, '\n');
1090 overlapping_strcpy(pattern_space, tmp + 1);
1094 /* discard this line. */
1098 /* Substitute with regex */
1100 if (!do_subst_command(sed_cmd, &pattern_space))
1104 /* handle p option */
1106 sed_puts(pattern_space, last_gets_char);
1107 /* handle w option */
1108 if (sed_cmd->sw_file)
1110 pattern_space, sed_cmd->sw_file,
1111 &sed_cmd->sw_last_char, last_gets_char);
1114 /* Append line to linked list to be printed later */
1116 append(sed_cmd->string);
1119 /* Insert text before this line */
1121 sed_puts(sed_cmd->string, '\n');
1124 /* Cut and paste text (replace) */
1126 /* Only triggers on last line of a matching range. */
1127 if (!sed_cmd->in_match)
1128 sed_puts(sed_cmd->string, '\n');
1131 /* Read file, append contents to output */
1135 rfile = fopen_for_read(sed_cmd->string);
1139 while ((line = xmalloc_fgetline(rfile))
1142 xprint_and_close_file(rfile);
1148 /* Write pattern space to file. */
1151 pattern_space, sed_cmd->sw_file,
1152 &sed_cmd->sw_last_char, last_gets_char);
1155 /* Read next line from input */
1158 sed_puts(pattern_space, last_gets_char);
1160 free(pattern_space);
1161 pattern_space = next_line;
1162 last_gets_char = next_gets_char;
1163 next_line = get_next_line(&next_gets_char);
1170 /* Quit. End of script, end of input. */
1172 /* Exit the outer while loop */
1175 goto discard_commands;
1177 /* Append the next line to the current line */
1181 /* If no next line, jump to end of script and exit. */
1182 /* http://www.gnu.org/software/sed/manual/sed.html:
1183 * "Most versions of sed exit without printing anything
1184 * when the N command is issued on the last line of
1185 * a file. GNU sed prints pattern space before exiting
1186 * unless of course the -n command switch has been
1187 * specified. This choice is by design."
1189 if (next_line == NULL) {
1190 //goto discard_line;
1191 goto discard_commands; /* GNU behavior */
1193 /* Append next_line, read new next_line. */
1194 len = strlen(pattern_space);
1195 pattern_space = xrealloc(pattern_space, len + strlen(next_line) + 2);
1196 pattern_space[len] = '\n';
1197 strcpy(pattern_space + len+1, next_line);
1198 last_gets_char = next_gets_char;
1199 next_line = get_next_line(&next_gets_char);
1204 /* Test/branch if substitution occurred */
1206 if (!substituted) break;
1209 /* Test/branch if substitution didn't occur */
1211 if (substituted) break;
1213 /* Branch to label */
1215 if (!sed_cmd->string) goto discard_commands;
1216 else sed_cmd = branch_to(sed_cmd->string);
1218 /* Transliterate characters */
1222 for (i = 0; pattern_space[i]; i++) {
1223 for (j = 0; sed_cmd->string[j]; j += 2) {
1224 if (pattern_space[i] == sed_cmd->string[j]) {
1225 pattern_space[i] = sed_cmd->string[j + 1];
1233 case 'g': /* Replace pattern space with hold space */
1234 free(pattern_space);
1235 pattern_space = xstrdup(G.hold_space ? G.hold_space : "");
1237 case 'G': /* Append newline and hold space to pattern space */
1239 int pattern_space_size = 2;
1240 int hold_space_size = 0;
1243 pattern_space_size += strlen(pattern_space);
1245 hold_space_size = strlen(G.hold_space);
1246 pattern_space = xrealloc(pattern_space,
1247 pattern_space_size + hold_space_size);
1248 if (pattern_space_size == 2)
1249 pattern_space[0] = 0;
1250 strcat(pattern_space, "\n");
1252 strcat(pattern_space, G.hold_space);
1253 last_gets_char = '\n';
1257 case 'h': /* Replace hold space with pattern space */
1259 G.hold_space = xstrdup(pattern_space);
1261 case 'H': /* Append newline and pattern space to hold space */
1263 int hold_space_size = 2;
1264 int pattern_space_size = 0;
1267 hold_space_size += strlen(G.hold_space);
1269 pattern_space_size = strlen(pattern_space);
1270 G.hold_space = xrealloc(G.hold_space,
1271 hold_space_size + pattern_space_size);
1273 if (hold_space_size == 2)
1275 strcat(G.hold_space, "\n");
1277 strcat(G.hold_space, pattern_space);
1281 case 'x': /* Exchange hold and pattern space */
1283 char *tmp = pattern_space;
1284 pattern_space = G.hold_space ? G.hold_space : xzalloc(1);
1285 last_gets_char = '\n';
1290 } /* for each cmd */
1293 * Exit point from sedding...
1296 /* we will print the line unless we were told to be quiet ('-n')
1297 or if the line was suppressed (ala 'd'elete) */
1299 sed_puts(pattern_space, last_gets_char);
1301 /* Delete and such jump here. */
1304 free(pattern_space);
1309 /* It is possible to have a command line argument with embedded
1310 * newlines. This counts as multiple command lines.
1311 * However, newline can be escaped: 's/e/z\<newline>z/'
1312 * We check for this.
1315 static void add_cmd_block(char *cmdstr)
1319 cmdstr = sv = xstrdup(cmdstr);
1321 eol = strchr(cmdstr, '\n');
1324 /* Count preceding slashes */
1328 while (sl != cmdstr && *--sl == '\\')
1330 /* Odd number of preceding slashes - newline is escaped */
1332 overlapping_strcpy(eol - 1, eol);
1333 eol = strchr(eol, '\n');
1344 int sed_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1345 int sed_main(int argc UNUSED_PARAM, char **argv)
1348 llist_t *opt_e, *opt_f;
1349 int status = EXIT_SUCCESS;
1353 /* destroy command strings on exit */
1354 if (ENABLE_FEATURE_CLEAN_UP) atexit(sed_free_and_close_stuff);
1356 /* Lie to autoconf when it starts asking stupid questions. */
1357 if (argv[1] && !strcmp(argv[1], "--version")) {
1358 puts("This is not GNU sed version 4.0");
1362 /* do normal option parsing */
1363 opt_e = opt_f = NULL;
1364 opt_complementary = "e::f::" /* can occur multiple times */
1365 "nn"; /* count -n */
1366 /* -i must be first, to match OPT_in_place definition */
1367 opt = getopt32(argv, "irne:f:", &opt_e, &opt_f,
1368 &G.be_quiet); /* counter for -n */
1371 if (opt & OPT_in_place) { // -i
1372 atexit(cleanup_outname);
1374 if (opt & 0x2) G.regex_type |= REG_EXTENDED; // -r
1375 //if (opt & 0x4) G.be_quiet++; // -n
1376 while (opt_e) { // -e
1377 add_cmd_block(llist_pop(&opt_e));
1379 while (opt_f) { // -f
1382 cmdfile = xfopen_for_read(llist_pop(&opt_f));
1383 while ((line = xmalloc_fgetline(cmdfile)) != NULL) {
1389 /* if we didn't get a pattern from -e or -f, use argv[0] */
1390 if (!(opt & 0x18)) {
1393 add_cmd_block(*argv++);
1395 /* Flush any unfinished commands. */
1398 /* By default, we write to stdout */
1399 G.nonstdout = stdout;
1401 /* argv[0..(argc-1)] should be names of file to process. If no
1402 * files were specified or '-' was specified, take input from stdin.
1403 * Otherwise, we process all the files specified. */
1404 if (argv[0] == NULL) {
1405 if (opt & OPT_in_place)
1406 bb_error_msg_and_die(bb_msg_requires_arg, "-i");
1407 add_input_file(stdin);
1412 for (i = 0; argv[i]; i++) {
1413 struct stat statbuf;
1416 if (LONE_DASH(argv[i]) && !(opt & OPT_in_place)) {
1417 add_input_file(stdin);
1421 file = fopen_or_warn(argv[i], "r");
1423 status = EXIT_FAILURE;
1426 if (!(opt & OPT_in_place)) {
1427 add_input_file(file);
1431 G.outname = xasprintf("%sXXXXXX", argv[i]);
1432 nonstdoutfd = xmkstemp(G.outname);
1433 G.nonstdout = xfdopen_for_write(nonstdoutfd);
1435 /* Set permissions/owner of output file */
1436 fstat(fileno(file), &statbuf);
1437 /* chmod'ing AFTER chown would preserve suid/sgid bits,
1438 * but GNU sed 4.2.1 does not preserve them either */
1439 fchmod(nonstdoutfd, statbuf.st_mode);
1440 fchown(nonstdoutfd, statbuf.st_uid, statbuf.st_gid);
1441 add_input_file(file);
1443 fclose(G.nonstdout);
1445 G.nonstdout = stdout;
1446 /* unlink(argv[i]); */
1447 xrename(G.outname, argv[i]);
1451 /* Here, to handle "sed 'cmds' nonexistent_file" case we did:
1452 * if (G.current_input_file >= G.input_file_count)
1454 * but it's not needed since process_files() works correctly
1455 * in this case too. */