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 char* 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
57 * http://www.opengroup.org/onlinepubs/007904975/utilities/sed.html
58 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html
65 //config: sed is used to perform text transformations on a file
66 //config: or input from a pipeline.
68 //kbuild:lib-$(CONFIG_SED) += sed.o
70 //applet:IF_SED(APPLET(sed, BB_DIR_BIN, BB_SUID_DROP))
72 //usage:#define sed_trivial_usage
73 //usage: "[-inrE] [-f FILE]... [-e CMD]... [FILE]...\n"
74 //usage: "or: sed [-inrE] CMD [FILE]..."
75 //usage:#define sed_full_usage "\n\n"
76 //usage: " -e CMD Add CMD to sed commands to be executed"
77 //usage: "\n -f FILE Add FILE contents to sed commands to be executed"
78 //usage: "\n -i[SFX] Edit files in-place (otherwise sends to stdout)"
79 //usage: "\n Optionally back files up, appending SFX"
80 //usage: "\n -n Suppress automatic printing of pattern space"
81 //usage: "\n -r,-E Use extended regex syntax"
83 //usage: "\nIf no -e or -f, the first non-option argument is the sed command string."
84 //usage: "\nRemaining arguments are input files (stdin if none)."
86 //usage:#define sed_example_usage
87 //usage: "$ echo \"foo\" | sed -e 's/f[a-zA-Z]o/bar/g'\n"
94 # define dbg(...) bb_error_msg(__VA_ARGS__)
96 # define dbg(...) ((void)0)
101 OPT_in_place = 1 << 0,
104 /* Each sed command turns into one of these structures. */
105 typedef struct sed_cmd_s {
106 /* Ordered by alignment requirements: currently 36 bytes on x86 */
107 struct sed_cmd_s *next; /* Next command (linked list, NULL terminated) */
109 /* address storage */
110 regex_t *beg_match; /* sed -e '/match/cmd' */
111 regex_t *end_match; /* sed -e '/match/,/end_match/cmd' */
112 regex_t *sub_match; /* For 's/sub_match/string/' */
113 int beg_line; /* 'sed 1p' 0 == apply commands to all lines */
114 int beg_line_orig; /* copy of the above, needed for -i */
115 int end_line; /* 'sed 1,3p' 0 == one line only. -1 = last line ($) */
117 FILE *sw_file; /* File (sw) command writes to, -1 for none. */
118 char *string; /* Data string for (saicytb) commands. */
120 unsigned which_match; /* (s) Which match to replace (0 for all) */
122 /* Bitfields (gcc won't group them if we don't) */
123 unsigned invert:1; /* the '!' after the address */
124 unsigned in_match:1; /* Next line also included in match? */
125 unsigned sub_p:1; /* (s) print option */
127 char sw_last_char; /* Last line written by (sw) had no '\n' */
130 char cmd; /* The command char: abcdDgGhHilnNpPqrstwxy:={} */
133 static const char semicolon_whitespace[] ALIGN1 = "; \n\r\t\v";
137 int be_quiet, regex_type;
140 char *outname, *hold_space;
143 /* list of input files */
144 int input_file_count, current_input_file;
145 const char **input_file_list;
148 regmatch_t regmatch[10];
149 regex_t *previous_regex_ptr;
151 /* linked list of sed commands */
152 sed_cmd_t *sed_cmd_head, **sed_cmd_tail;
154 /* linked list of append lines */
155 llist_t *append_head;
160 char *buf; /* Space to hold string */
161 int idx; /* Space used */
162 int len; /* Space allocated */
165 #define G (*(struct globals*)&bb_common_bufsiz1)
166 struct BUG_G_too_big {
167 char BUG_G_too_big[sizeof(G) <= COMMON_BUFSIZE ? 1 : -1];
169 #define INIT_G() do { \
170 G.sed_cmd_tail = &G.sed_cmd_head; \
174 #if ENABLE_FEATURE_CLEAN_UP
175 static void sed_free_and_close_stuff(void)
177 sed_cmd_t *sed_cmd = G.sed_cmd_head;
179 llist_free(G.append_head, free);
182 sed_cmd_t *sed_cmd_next = sed_cmd->next;
184 if (sed_cmd->sw_file)
185 xprint_and_close_file(sed_cmd->sw_file);
187 if (sed_cmd->beg_match) {
188 regfree(sed_cmd->beg_match);
189 free(sed_cmd->beg_match);
191 if (sed_cmd->end_match) {
192 regfree(sed_cmd->end_match);
193 free(sed_cmd->end_match);
195 if (sed_cmd->sub_match) {
196 regfree(sed_cmd->sub_match);
197 free(sed_cmd->sub_match);
199 free(sed_cmd->string);
201 sed_cmd = sed_cmd_next;
207 fclose(G.current_fp);
210 void sed_free_and_close_stuff(void);
213 /* If something bad happens during -i operation, delete temp file */
215 static void cleanup_outname(void)
217 if (G.outname) unlink(G.outname);
220 /* strcpy, replacing "\from" with 'to'. If to is NUL, replacing "\any" with 'any' */
222 static void parse_escapes(char *dest, const char *string, int len, char from, char to)
227 if (string[i] == '\\') {
228 if (!to || string[i+1] == from) {
229 *dest++ = to ? to : string[i+1];
233 *dest++ = string[i++];
235 /* TODO: is it safe wrt a string with trailing '\\' ? */
236 *dest++ = string[i++];
241 static char *copy_parsing_escapes(const char *string, int len)
244 char *dest = xmalloc(len + 1);
246 /* sed recognizes \n */
247 /* GNU sed also recognizes \t and \r */
248 for (s = "\nn\tt\rr"; *s; s += 2) {
249 parse_escapes(dest, string, len, s[1], s[0]);
258 * index_of_next_unescaped_regexp_delim - walks left to right through a string
259 * beginning at a specified index and returns the index of the next regular
260 * expression delimiter (typically a forward slash ('/')) not preceded by
261 * a backslash ('\'). A negative delimiter disables square bracket checking.
263 static int index_of_next_unescaped_regexp_delim(int delimiter, const char *str)
272 delimiter = -delimiter;
275 for (; (ch = str[idx]) != '\0'; idx++) {
278 && !(bracket == idx - 1 || (bracket == idx - 2 && str[idx - 1] == '^'))
286 else if (bracket == -1 && ch == '[')
288 else if (ch == delimiter)
292 /* if we make it to here, we've hit the end of the string */
293 bb_error_msg_and_die("unmatched '%c'", delimiter);
297 * Returns the index of the third delimiter
299 static int parse_regex_delim(const char *cmdstr, char **match, char **replace)
301 const char *cmdstr_ptr = cmdstr;
302 unsigned char delimiter;
305 /* verify that the 's' or 'y' is followed by something. That something
306 * (typically a 'slash') is now our regexp delimiter... */
308 bb_error_msg_and_die("bad format in substitution expression");
309 delimiter = *cmdstr_ptr++;
311 /* save the match string */
312 idx = index_of_next_unescaped_regexp_delim(delimiter, cmdstr_ptr);
313 *match = copy_parsing_escapes(cmdstr_ptr, idx);
315 /* save the replacement string */
316 cmdstr_ptr += idx + 1;
317 idx = index_of_next_unescaped_regexp_delim(- (int)delimiter, cmdstr_ptr);
318 *replace = copy_parsing_escapes(cmdstr_ptr, idx);
320 return ((cmdstr_ptr - cmdstr) + idx);
324 * returns the index in the string just past where the address ends.
326 static int get_address(const char *my_str, int *linenum, regex_t ** regex)
328 const char *pos = my_str;
330 if (isdigit(*my_str)) {
331 *linenum = strtol(my_str, (char**)&pos, 10);
332 /* endstr shouldnt ever equal NULL */
333 } else if (*my_str == '$') {
336 } else if (*my_str == '/' || *my_str == '\\') {
344 next = index_of_next_unescaped_regexp_delim(delimiter, ++pos);
345 temp = copy_parsing_escapes(pos, next);
346 *regex = xzalloc(sizeof(regex_t));
347 xregcomp(*regex, temp, G.regex_type);
349 /* Move position to next character after last delimiter */
355 /* Grab a filename. Whitespace at start is skipped, then goes to EOL. */
356 static int parse_file_cmd(/*sed_cmd_t *sed_cmd,*/ const char *filecmdstr, char **retval)
358 int start = 0, idx, hack = 0;
360 /* Skip whitespace, then grab filename to end of line */
361 while (isspace(filecmdstr[start]))
364 while (filecmdstr[idx] && filecmdstr[idx] != '\n')
367 /* If lines glued together, put backslash back. */
368 if (filecmdstr[idx] == '\n')
371 bb_error_msg_and_die("empty filename");
372 *retval = xstrndup(filecmdstr+start, idx-start+hack+1);
374 (*retval)[idx] = '\\';
379 static int parse_subst_cmd(sed_cmd_t *sed_cmd, const char *substr)
381 int cflags = G.regex_type;
386 * A substitution command should look something like this:
387 * s/match/replace/ #gIpw
391 idx = parse_regex_delim(substr, &match, &sed_cmd->string);
393 /* determine the number of back references in the match string */
394 /* Note: we compute this here rather than in the do_subst_command()
395 * function to save processor time, at the expense of a little more memory
396 * (4 bits) per sed_cmd */
398 /* process the flags */
400 sed_cmd->which_match = 1;
401 while (substr[++idx]) {
402 /* Parse match number */
403 if (isdigit(substr[idx])) {
404 if (match[0] != '^') {
405 /* Match 0 treated as all, multiple matches we take the last one. */
406 const char *pos = substr + idx;
407 /* FIXME: error check? */
408 sed_cmd->which_match = (unsigned)strtol(substr+idx, (char**) &pos, 10);
414 if (isspace(substr[idx]))
417 switch (substr[idx]) {
418 /* Replace all occurrences */
421 sed_cmd->which_match = 0;
423 /* Print pattern space */
431 idx += parse_file_cmd(/*sed_cmd,*/ substr+idx, &temp);
434 /* Ignore case (gnu exension) */
440 // while (substr[++idx]) continue;
441 idx += strlen(substr + idx); // same
448 bb_error_msg_and_die("bad option in substitution expression");
452 /* compile the match string into a regex */
453 if (*match != '\0') {
454 /* If match is empty, we use last regex used at runtime */
455 sed_cmd->sub_match = xzalloc(sizeof(regex_t));
456 dbg("xregcomp('%s',%x)", match, cflags);
457 xregcomp(sed_cmd->sub_match, match, cflags);
466 * Process the commands arguments
468 static const char *parse_cmd_args(sed_cmd_t *sed_cmd, const char *cmdstr)
470 static const char cmd_letters[] = "saicrw:btTydDgGhHlnNpPqx={}";
501 struct chk { char chk[sizeof(cmd_letters)-1 == IDX_nul ? 1 : -1]; };
503 unsigned idx = strchrnul(cmd_letters, sed_cmd->cmd) - cmd_letters;
505 /* handle (s)ubstitution command */
507 cmdstr += parse_subst_cmd(sed_cmd, cmdstr);
509 /* handle edit cmds: (a)ppend, (i)nsert, and (c)hange */
510 else if (idx <= IDX_c) { /* a,i,c */
511 if (idx < IDX_c) { /* a,i */
512 if (sed_cmd->end_line || sed_cmd->end_match)
513 bb_error_msg_and_die("command '%c' uses only one address", sed_cmd->cmd);
516 if (*cmdstr == '\n' || *cmdstr == '\\') {
520 if (!isspace(*cmdstr))
524 sed_cmd->string = xstrdup(cmdstr);
525 /* "\anychar" -> "anychar" */
526 parse_escapes(sed_cmd->string, sed_cmd->string, strlen(cmdstr), '\0', '\0');
527 cmdstr += strlen(cmdstr);
529 /* handle file cmds: (r)ead */
530 else if (idx <= IDX_w) { /* r,w */
531 if (idx < IDX_w) { /* r */
532 if (sed_cmd->end_line || sed_cmd->end_match)
533 bb_error_msg_and_die("command '%c' uses only one address", sed_cmd->cmd);
535 cmdstr += parse_file_cmd(/*sed_cmd,*/ cmdstr, &sed_cmd->string);
536 if (sed_cmd->cmd == 'w') {
537 sed_cmd->sw_file = xfopen_for_write(sed_cmd->string);
538 sed_cmd->sw_last_char = '\n';
541 /* handle branch commands */
542 else if (idx <= IDX_T) { /* :,b,t,T */
545 cmdstr = skip_whitespace(cmdstr);
546 length = strcspn(cmdstr, semicolon_whitespace);
548 sed_cmd->string = xstrndup(cmdstr, length);
552 /* translation command */
553 else if (idx == IDX_y) {
554 char *match, *replace;
557 cmdstr += parse_regex_delim(cmdstr, &match, &replace)+1;
558 /* \n already parsed, but \delimiter needs unescaping. */
559 parse_escapes(match, match, strlen(match), i, i);
560 parse_escapes(replace, replace, strlen(replace), i, i);
562 sed_cmd->string = xzalloc((strlen(match) + 1) * 2);
563 for (i = 0; match[i] && replace[i]; i++) {
564 sed_cmd->string[i*2] = match[i];
565 sed_cmd->string[i*2+1] = replace[i];
570 /* if it wasnt a single-letter command that takes no arguments
571 * then it must be an invalid command.
573 else if (idx >= IDX_nul) { /* not d,D,g,G,h,H,l,n,N,p,P,q,x,=,{,} */
574 bb_error_msg_and_die("unsupported command %c", sed_cmd->cmd);
577 /* give back whatever's left over */
582 /* Parse address+command sets, skipping comment lines. */
584 static void add_cmd(const char *cmdstr)
589 /* Append this line to any unfinished line from last time. */
590 if (G.add_cmd_line) {
591 char *tp = xasprintf("%s\n%s", G.add_cmd_line, cmdstr);
592 free(G.add_cmd_line);
593 cmdstr = G.add_cmd_line = tp;
596 /* If this line ends with unescaped backslash, request next line. */
597 n = len = strlen(cmdstr);
598 while (n && cmdstr[n-1] == '\\')
600 if ((len - n) & 1) { /* if odd number of trailing backslashes */
602 G.add_cmd_line = xstrdup(cmdstr);
603 G.add_cmd_line[len-1] = '\0';
607 /* Loop parsing all commands in this line. */
609 /* Skip leading whitespace and semicolons */
610 cmdstr += strspn(cmdstr, semicolon_whitespace);
612 /* If no more commands, exit. */
615 /* if this is a comment, jump past it and keep going */
616 if (*cmdstr == '#') {
617 /* "#n" is the same as using -n on the command line */
618 if (cmdstr[1] == 'n')
620 cmdstr = strpbrk(cmdstr, "\n\r");
626 * format is: [addr][,addr][!]cmd
631 sed_cmd = xzalloc(sizeof(sed_cmd_t));
633 /* first part (if present) is an address: either a '$', a number or a /regex/ */
634 cmdstr += get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
635 sed_cmd->beg_line_orig = sed_cmd->beg_line;
637 /* second part (if present) will begin with a comma */
638 if (*cmdstr == ',') {
642 idx = get_address(cmdstr, &sed_cmd->end_line, &sed_cmd->end_match);
644 bb_error_msg_and_die("no address after comma");
648 /* skip whitespace before the command */
649 cmdstr = skip_whitespace(cmdstr);
651 /* Check for inversion flag */
652 if (*cmdstr == '!') {
656 /* skip whitespace before the command */
657 cmdstr = skip_whitespace(cmdstr);
660 /* last part (mandatory) will be a command */
662 bb_error_msg_and_die("missing command");
663 sed_cmd->cmd = *cmdstr++;
664 cmdstr = parse_cmd_args(sed_cmd, cmdstr);
666 /* cmdstr now points past args.
667 * GNU sed requires a separator, if there are more commands,
668 * else it complains "char N: extra characters after command".
669 * Example: "sed 'p;d'". We also allow "sed 'pd'".
672 /* Add the command to the command array */
673 *G.sed_cmd_tail = sed_cmd;
674 G.sed_cmd_tail = &sed_cmd->next;
677 /* If we glued multiple lines together, free the memory. */
678 free(G.add_cmd_line);
679 G.add_cmd_line = NULL;
682 /* Append to a string, reallocating memory as necessary. */
686 static void pipe_putc(char c)
688 if (G.pipeline.idx == G.pipeline.len) {
689 G.pipeline.buf = xrealloc(G.pipeline.buf,
690 G.pipeline.len + PIPE_GROW);
691 G.pipeline.len += PIPE_GROW;
693 G.pipeline.buf[G.pipeline.idx++] = c;
696 static void do_subst_w_backrefs(char *line, char *replace)
700 /* go through the replacement string */
701 for (i = 0; replace[i]; i++) {
702 /* if we find a backreference (\1, \2, etc.) print the backref'ed text */
703 if (replace[i] == '\\') {
704 unsigned backref = replace[++i] - '0';
706 /* print out the text held in G.regmatch[backref] */
707 if (G.regmatch[backref].rm_so != -1) {
708 j = G.regmatch[backref].rm_so;
709 while (j < G.regmatch[backref].rm_eo)
710 pipe_putc(line[j++]);
714 /* I _think_ it is impossible to get '\' to be
715 * the last char in replace string. Thus we dont check
716 * for replace[i] == NUL. (counterexample anyone?) */
717 /* if we find a backslash escaped character, print the character */
718 pipe_putc(replace[i]);
721 /* if we find an unescaped '&' print out the whole matched text. */
722 if (replace[i] == '&') {
723 j = G.regmatch[0].rm_so;
724 while (j < G.regmatch[0].rm_eo)
725 pipe_putc(line[j++]);
728 /* Otherwise just output the character. */
729 pipe_putc(replace[i]);
733 static int do_subst_command(sed_cmd_t *sed_cmd, char **line_p)
735 char *line = *line_p;
736 unsigned match_count = 0;
738 bool prev_match_empty = 1;
739 bool tried_at_eol = 0;
740 regex_t *current_regex;
742 current_regex = sed_cmd->sub_match;
743 /* Handle empty regex. */
744 if (!current_regex) {
745 current_regex = G.previous_regex_ptr;
747 bb_error_msg_and_die("no previous regexp");
749 G.previous_regex_ptr = current_regex;
751 /* Find the first match */
752 dbg("matching '%s'", line);
753 if (REG_NOMATCH == regexec(current_regex, line, 10, G.regmatch, 0)) {
759 /* Initialize temporary output buffer. */
760 G.pipeline.buf = xmalloc(PIPE_GROW);
761 G.pipeline.len = PIPE_GROW;
764 /* Now loop through, substituting for matches */
766 int start = G.regmatch[0].rm_so;
767 int end = G.regmatch[0].rm_eo;
772 /* If we aren't interested in this match, output old line to
773 * end of match and continue */
774 if (sed_cmd->which_match
775 && (sed_cmd->which_match != match_count)
777 for (i = 0; i < end; i++)
779 /* Null match? Print one more char */
780 if (start == end && *line)
785 /* Print everything before the match */
786 for (i = 0; i < start; i++)
789 /* Then print the substitution string,
790 * unless we just matched empty string after non-empty one.
791 * Example: string "cccd", pattern "c*", repl "R":
792 * result is "RdR", not "RRdR": first match "ccc",
793 * second is "" before "d", third is "" after "d".
794 * Second match is NOT replaced!
796 if (prev_match_empty || start != 0 || start != end) {
797 //dbg("%d %d %d", prev_match_empty, start, end);
798 dbg("inserting replacement at %d in '%s'", start, line);
799 do_subst_w_backrefs(line, sed_cmd->string);
800 /* Flag that something has changed */
803 dbg("NOT inserting replacement at %d in '%s'", start, line);
806 /* If matched string is empty (f.e. "c*" pattern),
807 * copy verbatim one char after it before attempting more matches
809 prev_match_empty = (start == end);
810 if (prev_match_empty) {
814 pipe_putc(line[end]);
819 /* Advance past the match */
820 dbg("line += %d", end);
823 /* if we're not doing this globally, get out now */
824 if (sed_cmd->which_match != 0)
827 /* Exit if we are at EOL and already tried matching at it */
834 //maybe (end ? REG_NOTBOL : 0) instead of unconditional REG_NOTBOL?
835 } while (regexec(current_regex, line, 10, G.regmatch, REG_NOTBOL) != REG_NOMATCH);
837 /* Copy rest of string into output pipeline */
846 *line_p = G.pipeline.buf;
850 /* Set command pointer to point to this label. (Does not handle null label.) */
851 static sed_cmd_t *branch_to(char *label)
855 for (sed_cmd = G.sed_cmd_head; sed_cmd; sed_cmd = sed_cmd->next) {
856 if (sed_cmd->cmd == ':' && sed_cmd->string && !strcmp(sed_cmd->string, label)) {
860 bb_error_msg_and_die("can't find label for jump to '%s'", label);
863 static void append(char *s)
865 llist_add_to_end(&G.append_head, s);
868 /* Output line of text. */
870 * The tricks with NO_EOL_CHAR and last_puts_char are there to emulate gnu sed.
871 * Without them, we had this:
875 * sed "s/i/z/" z1 z2 znull | hexdump -vC
878 * 00000000 74 68 7a 6e 67 79 0a 61 67 61 7a 6e |thzngy.agazn|
880 * 00000000 74 68 7a 6e 67 79 61 67 61 7a 6e |thzngyagazn|
886 static void puts_maybe_newline(char *s, FILE *file, char *last_puts_char, char last_gets_char)
888 char lpc = *last_puts_char;
890 /* Need to insert a '\n' between two files because first file's
891 * last line wasn't terminated? */
892 if (lpc != '\n' && lpc != '\0') {
898 /* 'x' - just something which is not '\n', '\0' or NO_EOL_CHAR */
902 /* had trailing '\0' and it was last char of file? */
903 if (last_gets_char == LAST_IS_NUL) {
907 /* had trailing '\n' or '\0'? */
908 if (last_gets_char != NO_EOL_CHAR) {
909 fputc(last_gets_char, file);
910 lpc = last_gets_char;
914 xfunc_error_retval = 4; /* It's what gnu sed exits with... */
915 bb_error_msg_and_die(bb_msg_write_error);
917 *last_puts_char = lpc;
920 static void flush_append(char *last_puts_char, char last_gets_char)
924 /* Output appended lines. */
925 while ((data = (char *)llist_pop(&G.append_head))) {
926 puts_maybe_newline(data, G.nonstdout, last_puts_char, last_gets_char);
931 /* Get next line of input from G.input_file_list, flushing append buffer and
932 * noting if we ran out of files without a newline on the last line we read.
934 static char *get_next_line(char *gets_char, char *last_puts_char, char last_gets_char)
940 flush_append(last_puts_char, last_gets_char);
942 /* will be returned if last line in the file
943 * doesn't end with either '\n' or '\0' */
945 for (; G.input_file_list[G.current_input_file]; G.current_input_file++) {
946 FILE *fp = G.current_fp;
948 const char *path = G.input_file_list[G.current_input_file];
950 if (path != bb_msg_standard_input) {
951 fp = fopen_or_warn(path, "r");
953 G.exitcode = EXIT_FAILURE;
959 /* Read line up to a newline or NUL byte, inclusive,
960 * return malloc'ed char[]. length of the chunk read
961 * is stored in len. NULL if EOF/error */
962 temp = bb_get_chunk_from_file(fp, &len);
964 /* len > 0 here, it's ok to do temp[len-1] */
965 char c = temp[len-1];
966 if (c == '\n' || c == '\0') {
977 /* else we put NO_EOL_CHAR into *gets_char */
980 /* NB: I had the idea of peeking next file(s) and returning
981 * NO_EOL_CHAR only if it is the *last* non-empty
982 * input file. But there is a case where this won't work:
983 * file1: "a woo\nb woo"
984 * file2: "c no\nd no"
985 * sed -ne 's/woo/bang/p' input1 input2 => "a bang\nb bang"
986 * (note: *no* newline after "b bang"!) */
988 /* Close this file and advance to next one */
989 fclose_if_not_stdin(fp);
996 #define sed_puts(s, n) (puts_maybe_newline(s, G.nonstdout, &last_puts_char, n))
998 static int beg_match(sed_cmd_t *sed_cmd, const char *pattern_space)
1000 int retval = sed_cmd->beg_match && !regexec(sed_cmd->beg_match, pattern_space, 0, NULL, 0);
1002 G.previous_regex_ptr = sed_cmd->beg_match;
1006 /* Process all the lines in all the files */
1008 static void process_files(void)
1010 char *pattern_space, *next_line;
1012 char last_puts_char = '\n';
1013 char last_gets_char, next_gets_char;
1017 /* Prime the pump */
1018 next_line = get_next_line(&next_gets_char, &last_puts_char, '\n' /*last_gets_char*/);
1020 /* Go through every line in each file */
1024 /* Advance to next line. Stop if out of lines. */
1025 pattern_space = next_line;
1028 last_gets_char = next_gets_char;
1030 /* Read one line in advance so we can act on the last line,
1031 * the '$' address */
1032 next_line = get_next_line(&next_gets_char, &last_puts_char, last_gets_char);
1035 /* For every line, go through all the commands */
1037 for (sed_cmd = G.sed_cmd_head; sed_cmd; sed_cmd = sed_cmd->next) {
1038 int old_matched, matched;
1040 old_matched = sed_cmd->in_match;
1042 /* Determine if this command matches this line: */
1044 dbg("match1:%d", sed_cmd->in_match);
1045 dbg("match2:%d", (!sed_cmd->beg_line && !sed_cmd->end_line
1046 && !sed_cmd->beg_match && !sed_cmd->end_match));
1047 dbg("match3:%d", (sed_cmd->beg_line > 0
1048 && (sed_cmd->end_line || sed_cmd->end_match
1049 ? (sed_cmd->beg_line <= linenum)
1050 : (sed_cmd->beg_line == linenum)
1053 dbg("match4:%d", (beg_match(sed_cmd, pattern_space)));
1054 dbg("match5:%d", (sed_cmd->beg_line == -1 && next_line == NULL));
1056 /* Are we continuing a previous multi-line match? */
1057 sed_cmd->in_match = sed_cmd->in_match
1058 /* Or is no range necessary? */
1059 || (!sed_cmd->beg_line && !sed_cmd->end_line
1060 && !sed_cmd->beg_match && !sed_cmd->end_match)
1061 /* Or did we match the start of a numerical range? */
1062 || (sed_cmd->beg_line > 0
1063 && (sed_cmd->end_line || sed_cmd->end_match
1064 /* note: even if end is numeric and is < linenum too,
1065 * GNU sed matches! We match too, therefore we don't
1066 * check here that linenum <= end.
1068 * printf '1\n2\n3\n4\n' | sed -n '1{N;N;d};1p;2,3p;3p;4p'
1069 * first three input lines are deleted;
1070 * 4th line is matched and printed
1071 * by "2,3" (!) and by "4" ranges
1073 ? (sed_cmd->beg_line <= linenum) /* N,end */
1074 : (sed_cmd->beg_line == linenum) /* N */
1077 /* Or does this line match our begin address regex? */
1078 || (beg_match(sed_cmd, pattern_space))
1079 /* Or did we match last line of input? */
1080 || (sed_cmd->beg_line == -1 && next_line == NULL);
1082 /* Snapshot the value */
1083 matched = sed_cmd->in_match;
1085 dbg("cmd:'%c' matched:%d beg_line:%d end_line:%d linenum:%d",
1086 sed_cmd->cmd, matched, sed_cmd->beg_line, sed_cmd->end_line, linenum);
1088 /* Is this line the end of the current match? */
1091 /* once matched, "n,xxx" range is dead, disabling it */
1092 if (sed_cmd->beg_line > 0) {
1093 sed_cmd->beg_line = -2;
1095 sed_cmd->in_match = !(
1096 /* has the ending line come, or is this a single address command? */
1098 ? sed_cmd->end_line == -1
1100 : (sed_cmd->end_line <= linenum)
1101 : !sed_cmd->end_match
1103 /* or does this line matches our last address regex */
1104 || (sed_cmd->end_match && old_matched
1105 && (regexec(sed_cmd->end_match,
1106 pattern_space, 0, NULL, 0) == 0)
1111 /* Skip blocks of commands we didn't match */
1112 if (sed_cmd->cmd == '{') {
1113 if (sed_cmd->invert ? matched : !matched) {
1114 unsigned nest_cnt = 0;
1116 if (sed_cmd->cmd == '{')
1118 if (sed_cmd->cmd == '}') {
1123 sed_cmd = sed_cmd->next;
1125 bb_error_msg_and_die("unterminated {");
1131 /* Okay, so did this line match? */
1132 if (sed_cmd->invert ? matched : !matched)
1135 /* Update last used regex in case a blank substitute BRE is found */
1136 if (sed_cmd->beg_match) {
1137 G.previous_regex_ptr = sed_cmd->beg_match;
1140 /* actual sedding */
1141 dbg("pattern_space:'%s' next_line:'%s' cmd:%c",
1142 pattern_space, next_line, sed_cmd->cmd);
1143 switch (sed_cmd->cmd) {
1145 /* Print line number */
1147 fprintf(G.nonstdout, "%d\n", linenum);
1150 /* Write the current pattern space up to the first newline */
1153 char *tmp = strchr(pattern_space, '\n');
1156 /* TODO: explain why '\n' below */
1157 sed_puts(pattern_space, '\n');
1164 /* Write the current pattern space to output */
1166 /* NB: we print this _before_ the last line
1167 * (of current file) is printed. Even if
1168 * that line is nonterminated, we print
1169 * '\n' here (gnu sed does the same) */
1170 sed_puts(pattern_space, '\n');
1172 /* Delete up through first newline */
1175 char *tmp = strchr(pattern_space, '\n');
1177 overlapping_strcpy(pattern_space, tmp + 1);
1181 /* discard this line. */
1185 /* Substitute with regex */
1187 if (!do_subst_command(sed_cmd, &pattern_space))
1189 dbg("do_subst_command succeeded:'%s'", pattern_space);
1192 /* handle p option */
1194 sed_puts(pattern_space, last_gets_char);
1195 /* handle w option */
1196 if (sed_cmd->sw_file)
1198 pattern_space, sed_cmd->sw_file,
1199 &sed_cmd->sw_last_char, last_gets_char);
1202 /* Append line to linked list to be printed later */
1204 append(xstrdup(sed_cmd->string));
1207 /* Insert text before this line */
1209 sed_puts(sed_cmd->string, '\n');
1212 /* Cut and paste text (replace) */
1214 /* Only triggers on last line of a matching range. */
1215 if (!sed_cmd->in_match)
1216 sed_puts(sed_cmd->string, '\n');
1219 /* Read file, append contents to output */
1223 rfile = fopen_for_read(sed_cmd->string);
1226 while ((line = xmalloc_fgetline(rfile))
1235 /* Write pattern space to file. */
1238 pattern_space, sed_cmd->sw_file,
1239 &sed_cmd->sw_last_char, last_gets_char);
1242 /* Read next line from input */
1245 sed_puts(pattern_space, last_gets_char);
1247 free(pattern_space);
1248 pattern_space = next_line;
1249 last_gets_char = next_gets_char;
1250 next_line = get_next_line(&next_gets_char, &last_puts_char, last_gets_char);
1257 /* Quit. End of script, end of input. */
1259 /* Exit the outer while loop */
1262 goto discard_commands;
1264 /* Append the next line to the current line */
1268 /* If no next line, jump to end of script and exit. */
1269 /* http://www.gnu.org/software/sed/manual/sed.html:
1270 * "Most versions of sed exit without printing anything
1271 * when the N command is issued on the last line of
1272 * a file. GNU sed prints pattern space before exiting
1273 * unless of course the -n command switch has been
1274 * specified. This choice is by design."
1276 if (next_line == NULL) {
1277 //goto discard_line;
1278 goto discard_commands; /* GNU behavior */
1280 /* Append next_line, read new next_line. */
1281 len = strlen(pattern_space);
1282 pattern_space = xrealloc(pattern_space, len + strlen(next_line) + 2);
1283 pattern_space[len] = '\n';
1284 strcpy(pattern_space + len+1, next_line);
1285 last_gets_char = next_gets_char;
1286 next_line = get_next_line(&next_gets_char, &last_puts_char, last_gets_char);
1291 /* Test/branch if substitution occurred */
1293 if (!substituted) break;
1296 /* Test/branch if substitution didn't occur */
1298 if (substituted) break;
1300 /* Branch to label */
1302 if (!sed_cmd->string) goto discard_commands;
1303 else sed_cmd = branch_to(sed_cmd->string);
1305 /* Transliterate characters */
1309 for (i = 0; pattern_space[i]; i++) {
1310 for (j = 0; sed_cmd->string[j]; j += 2) {
1311 if (pattern_space[i] == sed_cmd->string[j]) {
1312 pattern_space[i] = sed_cmd->string[j + 1];
1320 case 'g': /* Replace pattern space with hold space */
1321 free(pattern_space);
1322 pattern_space = xstrdup(G.hold_space ? G.hold_space : "");
1324 case 'G': /* Append newline and hold space to pattern space */
1326 int pattern_space_size = 2;
1327 int hold_space_size = 0;
1330 pattern_space_size += strlen(pattern_space);
1332 hold_space_size = strlen(G.hold_space);
1333 pattern_space = xrealloc(pattern_space,
1334 pattern_space_size + hold_space_size);
1335 if (pattern_space_size == 2)
1336 pattern_space[0] = 0;
1337 strcat(pattern_space, "\n");
1339 strcat(pattern_space, G.hold_space);
1340 last_gets_char = '\n';
1344 case 'h': /* Replace hold space with pattern space */
1346 G.hold_space = xstrdup(pattern_space);
1348 case 'H': /* Append newline and pattern space to hold space */
1350 int hold_space_size = 2;
1351 int pattern_space_size = 0;
1354 hold_space_size += strlen(G.hold_space);
1356 pattern_space_size = strlen(pattern_space);
1357 G.hold_space = xrealloc(G.hold_space,
1358 hold_space_size + pattern_space_size);
1360 if (hold_space_size == 2)
1362 strcat(G.hold_space, "\n");
1364 strcat(G.hold_space, pattern_space);
1368 case 'x': /* Exchange hold and pattern space */
1370 char *tmp = pattern_space;
1371 pattern_space = G.hold_space ? G.hold_space : xzalloc(1);
1372 last_gets_char = '\n';
1377 } /* for each cmd */
1380 * Exit point from sedding...
1383 /* we will print the line unless we were told to be quiet ('-n')
1384 or if the line was suppressed (ala 'd'elete) */
1386 sed_puts(pattern_space, last_gets_char);
1388 /* Delete and such jump here. */
1390 flush_append(&last_puts_char, last_gets_char);
1391 free(pattern_space);
1396 /* It is possible to have a command line argument with embedded
1397 * newlines. This counts as multiple command lines.
1398 * However, newline can be escaped: 's/e/z\<newline>z/'
1399 * add_cmd() handles this.
1402 static void add_cmd_block(char *cmdstr)
1406 cmdstr = sv = xstrdup(cmdstr);
1408 eol = strchr(cmdstr, '\n');
1417 static void add_input_file(const char *file)
1419 G.input_file_list = xrealloc_vector(G.input_file_list, 2, G.input_file_count);
1420 G.input_file_list[G.input_file_count++] = file;
1423 int sed_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1424 int sed_main(int argc UNUSED_PARAM, char **argv)
1427 llist_t *opt_e, *opt_f;
1430 #if ENABLE_LONG_OPTS
1431 static const char sed_longopts[] ALIGN1 =
1432 /* name has_arg short */
1433 "in-place\0" Optional_argument "i"
1434 "regexp-extended\0" No_argument "r"
1435 "quiet\0" No_argument "n"
1436 "silent\0" No_argument "n"
1437 "expression\0" Required_argument "e"
1438 "file\0" Required_argument "f";
1443 /* destroy command strings on exit */
1444 if (ENABLE_FEATURE_CLEAN_UP) atexit(sed_free_and_close_stuff);
1446 /* Lie to autoconf when it starts asking stupid questions. */
1447 if (argv[1] && strcmp(argv[1], "--version") == 0) {
1448 puts("This is not GNU sed version 4.0");
1452 /* do normal option parsing */
1453 opt_e = opt_f = NULL;
1455 opt_complementary = "e::f::" /* can occur multiple times */
1456 "nn"; /* count -n */
1458 IF_LONG_OPTS(applet_long_options = sed_longopts);
1460 /* -i must be first, to match OPT_in_place definition */
1461 /* -E is a synonym of -r:
1462 * GNU sed 4.2.1 mentions it in neither --help
1463 * nor manpage, but does recognize it.
1465 opt = getopt32(argv, "i::rEne:f:", &opt_i, &opt_e, &opt_f,
1466 &G.be_quiet); /* counter for -n */
1469 if (opt & OPT_in_place) { // -i
1470 atexit(cleanup_outname);
1473 G.regex_type |= REG_EXTENDED; // -r or -E
1475 // G.be_quiet++; // -n (implemented with a counter instead)
1476 while (opt_e) { // -e
1477 add_cmd_block(llist_pop(&opt_e));
1479 while (opt_f) { // -f
1482 cmdfile = xfopen_for_read(llist_pop(&opt_f));
1483 while ((line = xmalloc_fgetline(cmdfile)) != NULL) {
1489 /* if we didn't get a pattern from -e or -f, use argv[0] */
1490 if (!(opt & 0x30)) {
1493 add_cmd_block(*argv++);
1495 /* Flush any unfinished commands. */
1498 /* By default, we write to stdout */
1499 G.nonstdout = stdout;
1501 /* argv[0..(argc-1)] should be names of file to process. If no
1502 * files were specified or '-' was specified, take input from stdin.
1503 * Otherwise, we process all the files specified. */
1504 if (argv[0] == NULL) {
1505 if (opt & OPT_in_place)
1506 bb_error_msg_and_die(bb_msg_requires_arg, "-i");
1507 add_input_file(bb_msg_standard_input);
1511 for (i = 0; argv[i]; i++) {
1512 struct stat statbuf;
1516 if (LONE_DASH(argv[i]) && !(opt & OPT_in_place)) {
1517 add_input_file(bb_msg_standard_input);
1521 add_input_file(argv[i]);
1522 if (!(opt & OPT_in_place)) {
1526 /* -i: process each FILE separately: */
1528 G.outname = xasprintf("%sXXXXXX", argv[i]);
1529 nonstdoutfd = xmkstemp(G.outname);
1530 G.nonstdout = xfdopen_for_write(nonstdoutfd);
1532 /* Set permissions/owner of output file */
1533 stat(argv[i], &statbuf);
1534 /* chmod'ing AFTER chown would preserve suid/sgid bits,
1535 * but GNU sed 4.2.1 does not preserve them either */
1536 fchmod(nonstdoutfd, statbuf.st_mode);
1537 fchown(nonstdoutfd, statbuf.st_uid, statbuf.st_gid);
1540 fclose(G.nonstdout);
1541 G.nonstdout = stdout;
1544 char *backupname = xasprintf("%s%s", argv[i], opt_i);
1545 xrename(argv[i], backupname);
1548 /* else unlink(argv[i]); - rename below does this */
1549 xrename(G.outname, argv[i]); //TODO: rollback backup on error?
1553 /* Re-enable disabled range matches */
1554 for (sed_cmd = G.sed_cmd_head; sed_cmd; sed_cmd = sed_cmd->next) {
1555 sed_cmd->beg_line = sed_cmd->beg_line_orig;
1558 /* Here, to handle "sed 'cmds' nonexistent_file" case we did:
1559 * if (G.current_input_file[G.current_input_file] == NULL)
1560 * return G.exitcode;
1561 * but it's not needed since process_files() works correctly
1562 * in this case too. */