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 GPLv2 or later, 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 (bbg.sed_cmd_head/bbg.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
62 #include <unistd.h> /* for getopt() */
64 #include <ctype.h> /* for isspace() */
70 /* Each sed command turns into one of these structures. */
71 typedef struct sed_cmd_s {
72 /* Ordered by alignment requirements: currently 36 bytes on x86 */
75 regex_t *beg_match; /* sed -e '/match/cmd' */
76 regex_t *end_match; /* sed -e '/match/,/end_match/cmd' */
77 regex_t *sub_match; /* For 's/sub_match/string/' */
78 int beg_line; /* 'sed 1p' 0 == apply commands to all lines */
79 int end_line; /* 'sed 1,3p' 0 == one line only. -1 = last line ($) */
81 FILE *file; /* File (sw) command writes to, -1 for none. */
82 char *string; /* Data string for (saicytb) commands. */
84 unsigned short which_match; /* (s) Which match to replace (0 for all) */
86 /* Bitfields (gcc won't group them if we don't) */
87 unsigned int invert:1; /* the '!' after the address */
88 unsigned int in_match:1; /* Next line also included in match? */
89 unsigned int no_newline:1; /* Last line written by (sw) had no '\n' */
90 unsigned int sub_p:1; /* (s) print option */
93 char cmd; /* The command char: abcdDgGhHilnNpPqrstwxy:={} */
94 struct sed_cmd_s *next; /* Next command (linked list, NULL terminated) */
97 static const char bad_format_in_subst[] =
98 "bad format in substitution expression";
99 static const char *const semicolon_whitespace = "; \n\r\t\v";
104 int be_quiet, in_place, regex_type;
106 char *outname, *hold_space;
108 /* List of input files */
109 int input_file_count,current_input_file;
110 FILE **input_file_list;
112 regmatch_t regmatch[10];
113 regex_t *previous_regex_ptr;
115 /* linked list of sed commands */
116 sed_cmd_t sed_cmd_head, *sed_cmd_tail;
118 /* Linked list of append lines */
119 llist_t *append_head;
124 char *buf; /* Space to hold string */
125 int idx; /* Space used */
126 int len; /* Space allocated */
131 void sed_free_and_close_stuff(void);
132 #if ENABLE_FEATURE_CLEAN_UP
133 void sed_free_and_close_stuff(void)
135 sed_cmd_t *sed_cmd = bbg.sed_cmd_head.next;
137 llist_free_contents(bbg.append_head);
140 sed_cmd_t *sed_cmd_next = sed_cmd->next;
143 bb_xprint_and_close_file(sed_cmd->file);
145 if (sed_cmd->beg_match) {
146 regfree(sed_cmd->beg_match);
147 free(sed_cmd->beg_match);
149 if (sed_cmd->end_match) {
150 regfree(sed_cmd->end_match);
151 free(sed_cmd->end_match);
153 if (sed_cmd->sub_match) {
154 regfree(sed_cmd->sub_match);
155 free(sed_cmd->sub_match);
157 free(sed_cmd->string);
159 sed_cmd = sed_cmd_next;
162 if(bbg.hold_space) free(bbg.hold_space);
164 while(bbg.current_input_file<bbg.input_file_count)
165 fclose(bbg.input_file_list[bbg.current_input_file++]);
169 /* If something bad happens during -i operation, delete temp file */
171 static void cleanup_outname(void)
173 if(bbg.outname) unlink(bbg.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];
188 } else *(dest++)=string[i++];
190 *(dest++) = string[i++];
195 static char *copy_parsing_escapes(const char *string, int len)
197 char *dest=xmalloc(len+1);
199 parse_escapes(dest,string,len,'n','\n');
205 * index_of_next_unescaped_regexp_delim - walks left to right through a string
206 * beginning at a specified index and returns the index of the next regular
207 * expression delimiter (typically a forward * slash ('/')) not preceded by
210 static int index_of_next_unescaped_regexp_delim(const char delimiter,
218 for (; (ch = str[idx]); idx++) {
220 if (ch == ']' && !(bracket == idx - 1 || (bracket == idx - 2
221 && str[idx - 1] == '^')))
229 else if (ch == delimiter)
233 /* if we make it to here, we've hit the end of the string */
238 * Returns the index of the third delimiter
240 static int parse_regex_delim(const char *cmdstr, char **match, char **replace)
242 const char *cmdstr_ptr = cmdstr;
246 /* verify that the 's' or 'y' is followed by something. That something
247 * (typically a 'slash') is now our regexp delimiter... */
248 if (*cmdstr == '\0') bb_error_msg_and_die(bad_format_in_subst);
249 delimiter = *(cmdstr_ptr++);
251 /* save the match string */
252 idx = index_of_next_unescaped_regexp_delim(delimiter, cmdstr_ptr);
254 bb_error_msg_and_die(bad_format_in_subst);
256 *match = copy_parsing_escapes(cmdstr_ptr, idx);
258 /* save the replacement string */
259 cmdstr_ptr += idx + 1;
260 idx = index_of_next_unescaped_regexp_delim(delimiter, cmdstr_ptr);
262 bb_error_msg_and_die(bad_format_in_subst);
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(char *my_str, int *linenum, regex_t ** regex)
276 if (isdigit(*my_str)) {
277 *linenum = strtol(my_str, &pos, 10);
278 /* endstr shouldnt ever equal NULL */
279 } else if (*my_str == '$') {
282 } else if (*my_str == '/' || *my_str == '\\') {
287 if (*my_str == '\\') delimiter = *(++pos);
288 else delimiter = '/';
289 next = index_of_next_unescaped_regexp_delim(delimiter, ++pos);
291 bb_error_msg_and_die("unterminated match expression");
293 temp=copy_parsing_escapes(pos,next);
294 *regex = (regex_t *) xmalloc(sizeof(regex_t));
295 xregcomp(*regex, temp, bbg.regex_type|REG_NEWLINE);
297 /* Move position to next character after last delimiter */
303 /* Grab a filename. Whitespace at start is skipped, then goes to EOL. */
304 static int parse_file_cmd(sed_cmd_t *sed_cmd, const char *filecmdstr, char **retval)
306 int start = 0, idx, hack=0;
308 /* Skip whitespace, then grab filename to end of line */
309 while (isspace(filecmdstr[start])) start++;
311 while(filecmdstr[idx] && filecmdstr[idx]!='\n') idx++;
312 /* If lines glued together, put backslash back. */
313 if(filecmdstr[idx]=='\n') hack=1;
314 if(idx==start) bb_error_msg_and_die("Empty filename");
315 *retval = bb_xstrndup(filecmdstr+start, idx-start+hack+1);
316 if(hack) *(idx+*retval)='\\';
321 static int parse_subst_cmd(sed_cmd_t *const sed_cmd, char *substr)
323 int cflags = bbg.regex_type;
328 * A substitution command should look something like this:
329 * s/match/replace/ #gIpw
333 idx = parse_regex_delim(substr, &match, &sed_cmd->string);
335 /* determine the number of back references in the match string */
336 /* Note: we compute this here rather than in the do_subst_command()
337 * function to save processor time, at the expense of a little more memory
338 * (4 bits) per sed_cmd */
340 /* process the flags */
342 sed_cmd->which_match=1;
343 while (substr[++idx]) {
344 /* Parse match number */
345 if(isdigit(substr[idx])) {
347 /* Match 0 treated as all, multiple matches we take the last one. */
348 char *pos=substr+idx;
349 sed_cmd->which_match=(unsigned short)strtol(substr+idx,&pos,10);
355 if(isspace(substr[idx])) continue;
357 switch (substr[idx]) {
358 /* Replace all occurrences */
360 if (match[0] != '^') sed_cmd->which_match = 0;
362 /* Print pattern space */
370 idx+=parse_file_cmd(sed_cmd,substr+idx,&temp);
374 /* Ignore case (gnu exension) */
380 while(substr[++idx]);
387 bb_error_msg_and_die("bad option in substitution expression");
391 /* compile the match string into a regex */
392 if (*match != '\0') {
393 /* If match is empty, we use last regex used at runtime */
394 sed_cmd->sub_match = (regex_t *) xmalloc(sizeof(regex_t));
395 xregcomp(sed_cmd->sub_match, match, cflags);
403 * Process the commands arguments
405 static char *parse_cmd_args(sed_cmd_t *sed_cmd, char *cmdstr)
407 /* handle (s)ubstitution command */
408 if (sed_cmd->cmd == 's') cmdstr += parse_subst_cmd(sed_cmd, cmdstr);
409 /* handle edit cmds: (a)ppend, (i)nsert, and (c)hange */
410 else if (strchr("aic", sed_cmd->cmd)) {
411 if ((sed_cmd->end_line || sed_cmd->end_match) && sed_cmd->cmd != 'c')
413 ("only a beginning address can be specified for edit commands");
415 if(*cmdstr=='\n' || *cmdstr=='\\') {
418 } else if(isspace(*cmdstr)) cmdstr++;
421 sed_cmd->string = bb_xstrdup(cmdstr);
422 parse_escapes(sed_cmd->string,sed_cmd->string,strlen(cmdstr),0,0);
423 cmdstr += strlen(cmdstr);
424 /* handle file cmds: (r)ead */
425 } else if(strchr("rw", sed_cmd->cmd)) {
426 if (sed_cmd->end_line || sed_cmd->end_match)
427 bb_error_msg_and_die("Command only uses one address");
428 cmdstr += parse_file_cmd(sed_cmd, cmdstr, &sed_cmd->string);
429 if(sed_cmd->cmd=='w')
430 sed_cmd->file=bb_xfopen(sed_cmd->string,"w");
431 /* handle branch commands */
432 } else if (strchr(":btT", sed_cmd->cmd)) {
435 while(isspace(*cmdstr)) cmdstr++;
436 length = strcspn(cmdstr, semicolon_whitespace);
438 sed_cmd->string = bb_xstrndup(cmdstr, length);
442 /* translation command */
443 else if (sed_cmd->cmd == 'y') {
444 char *match, *replace;
447 cmdstr+=parse_regex_delim(cmdstr, &match, &replace)+1;
448 /* \n already parsed, but \delimiter needs unescaping. */
449 parse_escapes(match,match,strlen(match),i,i);
450 parse_escapes(replace,replace,strlen(replace),i,i);
452 sed_cmd->string = xcalloc(1, (strlen(match) + 1) * 2);
453 for (i = 0; match[i] && replace[i]; i++) {
454 sed_cmd->string[i * 2] = match[i];
455 sed_cmd->string[(i * 2) + 1] = replace[i];
460 /* if it wasnt a single-letter command that takes no arguments
461 * then it must be an invalid command.
463 else if (strchr("dDgGhHlnNpPqx={}", sed_cmd->cmd) == 0) {
464 bb_error_msg_and_die("Unsupported command %c", sed_cmd->cmd);
467 /* give back whatever's left over */
472 /* Parse address+command sets, skipping comment lines. */
474 static void add_cmd(char *cmdstr)
479 /* Append this line to any unfinished line from last time. */
480 if (bbg.add_cmd_line) {
481 cmdstr = bb_xasprintf("%s\n%s", bbg.add_cmd_line, cmdstr);
482 free(bbg.add_cmd_line);
483 bbg.add_cmd_line = cmdstr;
484 } else bbg.add_cmd_line=NULL;
486 /* If this line ends with backslash, request next line. */
488 if(temp && cmdstr[temp-1]=='\\') {
489 if (!bbg.add_cmd_line) bbg.add_cmd_line = bb_xstrdup(cmdstr);
490 bbg.add_cmd_line[temp-1] = 0;
494 /* Loop parsing all commands in this line. */
496 /* Skip leading whitespace and semicolons */
497 cmdstr += strspn(cmdstr, semicolon_whitespace);
499 /* If no more commands, exit. */
502 /* if this is a comment, jump past it and keep going */
503 if (*cmdstr == '#') {
504 /* "#n" is the same as using -n on the command line */
505 if (cmdstr[1] == 'n') bbg.be_quiet++;
506 if(!(cmdstr=strpbrk(cmdstr, "\n\r"))) break;
511 * format is: [addr][,addr][!]cmd
516 sed_cmd = xcalloc(1, sizeof(sed_cmd_t));
518 /* first part (if present) is an address: either a '$', a number or a /regex/ */
519 cmdstr += get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
521 /* second part (if present) will begin with a comma */
522 if (*cmdstr == ',') {
526 idx = get_address(cmdstr, &sed_cmd->end_line, &sed_cmd->end_match);
527 if (!idx) bb_error_msg_and_die("no address after comma\n");
531 /* skip whitespace before the command */
532 while (isspace(*cmdstr)) cmdstr++;
534 /* Check for inversion flag */
535 if (*cmdstr == '!') {
539 /* skip whitespace before the command */
540 while (isspace(*cmdstr)) cmdstr++;
543 /* last part (mandatory) will be a command */
544 if (!*cmdstr) bb_error_msg_and_die("missing command");
545 sed_cmd->cmd = *(cmdstr++);
546 cmdstr = parse_cmd_args(sed_cmd, cmdstr);
548 /* Add the command to the command array */
549 bbg.sed_cmd_tail->next = sed_cmd;
550 bbg.sed_cmd_tail = bbg.sed_cmd_tail->next;
553 /* If we glued multiple lines together, free the memory. */
554 free(bbg.add_cmd_line);
555 bbg.add_cmd_line = NULL;
558 /* Append to a string, reallocating memory as necessary. */
562 static void pipe_putc(char c)
564 if(bbg.pipeline.idx==bbg.pipeline.len) {
565 bbg.pipeline.buf = xrealloc(bbg.pipeline.buf,
566 bbg.pipeline.len + PIPE_GROW);
567 bbg.pipeline.len+=PIPE_GROW;
569 bbg.pipeline.buf[bbg.pipeline.idx++] = c;
572 static void do_subst_w_backrefs(const char *line, const char *replace)
576 /* go through the replacement string */
577 for (i = 0; replace[i]; i++) {
578 /* if we find a backreference (\1, \2, etc.) print the backref'ed * text */
579 if (replace[i] == '\\' && replace[i+1]>='0' && replace[i+1]<='9') {
580 int backref=replace[++i]-'0';
582 /* print out the text held in bbg.regmatch[backref] */
583 if(bbg.regmatch[backref].rm_so != -1)
584 for (j = bbg.regmatch[backref].rm_so;
585 j < bbg.regmatch[backref].rm_eo; j++) pipe_putc(line[j]);
588 /* if we find a backslash escaped character, print the character */
589 else if (replace[i] == '\\') pipe_putc(replace[++i]);
591 /* if we find an unescaped '&' print out the whole matched text. */
592 else if (replace[i] == '&')
593 for (j = bbg.regmatch[0].rm_so; j < bbg.regmatch[0].rm_eo; j++)
595 /* Otherwise just output the character. */
596 else pipe_putc(replace[i]);
600 static int do_subst_command(sed_cmd_t *sed_cmd, char **line)
602 char *oldline = *line;
605 regex_t *current_regex;
607 /* Handle empty regex. */
608 if (sed_cmd->sub_match == NULL) {
609 current_regex = bbg.previous_regex_ptr;
611 bb_error_msg_and_die("No previous regexp.");
612 } else bbg.previous_regex_ptr = current_regex = sed_cmd->sub_match;
614 /* Find the first match */
615 if(REG_NOMATCH==regexec(current_regex, oldline, 10, bbg.regmatch, 0))
618 /* Initialize temporary output buffer. */
619 bbg.pipeline.buf=xmalloc(PIPE_GROW);
620 bbg.pipeline.len=PIPE_GROW;
623 /* Now loop through, substituting for matches */
627 /* Work around bug in glibc regexec, demonstrated by:
628 echo " a.b" | busybox sed 's [^ .]* x g'
629 The match_count check is so not to break
630 echo "hi" | busybox sed 's/^/!/g' */
631 if(!bbg.regmatch[0].rm_so && !bbg.regmatch[0].rm_eo && match_count) {
632 pipe_putc(*(oldline++));
638 /* If we aren't interested in this match, output old line to
639 end of match and continue */
640 if(sed_cmd->which_match && sed_cmd->which_match!=match_count) {
641 for(i=0;i<bbg.regmatch[0].rm_eo;i++)
642 pipe_putc(oldline[i]);
646 /* print everything before the match */
647 for (i = 0; i < bbg.regmatch[0].rm_so; i++) pipe_putc(oldline[i]);
649 /* then print the substitution string */
650 do_subst_w_backrefs(oldline, sed_cmd->string);
652 /* advance past the match */
653 oldline += bbg.regmatch[0].rm_eo;
654 /* flag that something has changed */
657 /* if we're not doing this globally, get out now */
658 if (sed_cmd->which_match) break;
659 } while (*oldline && (regexec(current_regex, oldline, 10, bbg.regmatch, 0) != REG_NOMATCH));
661 /* Copy rest of string into output pipeline */
663 while(*oldline) pipe_putc(*(oldline++));
667 *line = bbg.pipeline.buf;
671 /* Set command pointer to point to this label. (Does not handle null label.) */
672 static sed_cmd_t *branch_to(const char *label)
676 for (sed_cmd = bbg.sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
677 if ((sed_cmd->cmd == ':') && (sed_cmd->string) && (strcmp(sed_cmd->string, label) == 0)) {
681 bb_error_msg_and_die("Can't find label for jump to `%s'", label);
684 static void append(char *s)
686 bbg.append_head = llist_add_to_end(bbg.append_head, bb_xstrdup(s));
689 static void flush_append(void)
693 /* Output appended lines. */
694 while((data = (char *)llist_pop(&bbg.append_head))) {
695 fprintf(bbg.nonstdout,"%s\n",data);
700 static void add_input_file(FILE *file)
702 bbg.input_file_list=xrealloc(bbg.input_file_list,
703 (bbg.input_file_count + 1) * sizeof(FILE *));
704 bbg.input_file_list[bbg.input_file_count++] = file;
707 /* Get next line of input from bbg.input_file_list, flushing append buffer and
708 * noting if we ran out of files without a newline on the last line we read.
710 static char *get_next_line(int *no_newline)
716 while (bbg.current_input_file<bbg.input_file_count) {
717 temp = bb_get_chunk_from_file(bbg.input_file_list[bbg.current_input_file],&len);
719 *no_newline = !(len && temp[len-1]=='\n');
720 if (!*no_newline) temp[len-1] = 0;
722 // Close this file and advance to next one
723 } else fclose(bbg.input_file_list[bbg.current_input_file++]);
729 /* Output line of text. missing_newline means the last line output did not
730 end with a newline. no_newline means this line does not end with a
733 static int puts_maybe_newline(char *s, FILE *file, int missing_newline, int no_newline)
735 if(missing_newline) fputc('\n',file);
737 if(!no_newline) fputc('\n',file);
740 fprintf(stderr,"Write failed.\n");
741 exit(4); /* It's what gnu sed exits with... */
747 #define sed_puts(s,n) missing_newline=puts_maybe_newline(s,bbg.nonstdout,missing_newline,n)
749 /* Process all the lines in all the files */
751 static void process_files(void)
753 char *pattern_space, *next_line;
754 int linenum = 0, missing_newline=0;
755 int no_newline,next_no_newline=0;
758 next_line = get_next_line(&next_no_newline);
760 /* go through every line in each file */
765 /* Advance to next line. Stop if out of lines. */
766 if(!(pattern_space=next_line)) break;
767 no_newline=next_no_newline;
769 /* Read one line in advance so we can act on the last line,
771 next_line = get_next_line(&next_no_newline);
774 /* for every line, go through all the commands */
775 for (sed_cmd = bbg.sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next)
777 int old_matched, matched;
779 old_matched = sed_cmd->in_match;
781 /* Determine if this command matches this line: */
783 /* Are we continuing a previous multi-line match? */
785 sed_cmd->in_match = sed_cmd->in_match
787 /* Or is no range necessary? */
788 || (!sed_cmd->beg_line && !sed_cmd->end_line
789 && !sed_cmd->beg_match && !sed_cmd->end_match)
791 /* Or did we match the start of a numerical range? */
792 || (sed_cmd->beg_line > 0 && (sed_cmd->beg_line == linenum))
794 /* Or does this line match our begin address regex? */
795 || (sed_cmd->beg_match &&
796 !regexec(sed_cmd->beg_match, pattern_space, 0, NULL, 0))
798 /* Or did we match last line of input? */
799 || (sed_cmd->beg_line == -1 && next_line == NULL);
801 /* Snapshot the value */
803 matched = sed_cmd->in_match;
805 /* Is this line the end of the current match? */
808 sed_cmd->in_match = !(
809 /* has the ending line come, or is this a single address command? */
811 sed_cmd->end_line==-1 ?
813 : sed_cmd->end_line<=linenum
814 : !sed_cmd->end_match)
815 /* or does this line matches our last address regex */
816 || (sed_cmd->end_match && old_matched && (regexec(sed_cmd->end_match, pattern_space, 0, NULL, 0) == 0))
820 /* Skip blocks of commands we didn't match. */
821 if (sed_cmd->cmd == '{') {
822 if(sed_cmd->invert ? matched : !matched)
823 while(sed_cmd && sed_cmd->cmd!='}') sed_cmd=sed_cmd->next;
824 if(!sed_cmd) bb_error_msg_and_die("Unterminated {");
828 /* Okay, so did this line match? */
829 if (sed_cmd->invert ? !matched : matched) {
830 /* Update last used regex in case a blank substitute BRE is found */
831 if (sed_cmd->beg_match) {
832 bbg.previous_regex_ptr = sed_cmd->beg_match;
836 switch (sed_cmd->cmd) {
838 /* Print line number */
840 fprintf(bbg.nonstdout,"%d\n", linenum);
843 /* Write the current pattern space up to the first newline */
846 char *tmp = strchr(pattern_space, '\n');
850 sed_puts(pattern_space,1);
857 /* Write the current pattern space to output */
859 sed_puts(pattern_space,no_newline);
861 /* Delete up through first newline */
864 char *tmp = strchr(pattern_space,'\n');
867 tmp=bb_xstrdup(tmp+1);
873 /* discard this line. */
877 /* Substitute with regex */
879 if(do_subst_command(sed_cmd, &pattern_space)) {
882 /* handle p option */
884 sed_puts(pattern_space,no_newline);
885 /* handle w option */
887 sed_cmd->no_newline=puts_maybe_newline(pattern_space, sed_cmd->file, sed_cmd->no_newline, no_newline);
892 /* Append line to linked list to be printed later */
895 append(sed_cmd->string);
899 /* Insert text before this line */
901 sed_puts(sed_cmd->string,1);
904 /* Cut and paste text (replace) */
906 /* Only triggers on last line of a matching range. */
907 if (!sed_cmd->in_match) sed_puts(sed_cmd->string,0);
910 /* Read file, append contents to output */
915 rfile = fopen(sed_cmd->string, "r");
919 while ((line = bb_get_chomped_line_from_file(rfile))
922 bb_xprint_and_close_file(rfile);
928 /* Write pattern space to file. */
930 sed_cmd->no_newline=puts_maybe_newline(pattern_space,sed_cmd->file, sed_cmd->no_newline,no_newline);
933 /* Read next line from input */
936 sed_puts(pattern_space,no_newline);
939 pattern_space = next_line;
940 no_newline=next_no_newline;
941 next_line = get_next_line(&next_no_newline);
947 /* Quit. End of script, end of input. */
949 /* Exit the outer while loop */
952 goto discard_commands;
954 /* Append the next line to the current line */
957 /* If no next line, jump to end of script and exit. */
958 if (next_line == NULL) {
959 /* Jump to end of script and exit */
963 /* append next_line, read new next_line. */
965 int len=strlen(pattern_space);
967 pattern_space = realloc(pattern_space, len + strlen(next_line) + 2);
968 pattern_space[len]='\n';
969 strcpy(pattern_space+len+1, next_line);
970 no_newline=next_no_newline;
971 next_line = get_next_line(&next_no_newline);
977 /* Test/branch if substitution occurred */
979 if(!substituted) break;
982 /* Test/branch if substitution didn't occur */
984 if (substituted) break;
986 /* Branch to label */
988 if (!sed_cmd->string) goto discard_commands;
989 else sed_cmd = branch_to(sed_cmd->string);
991 /* Transliterate characters */
996 for (i = 0; pattern_space[i]; i++) {
999 for (j = 0; sed_cmd->string[j]; j += 2) {
1000 if (pattern_space[i] == sed_cmd->string[j]) {
1001 pattern_space[i] = sed_cmd->string[j + 1];
1009 case 'g': /* Replace pattern space with hold space */
1010 free(pattern_space);
1011 pattern_space = bb_xstrdup(bbg.hold_space ? bbg.hold_space : "");
1013 case 'G': /* Append newline and hold space to pattern space */
1015 int pattern_space_size = 2;
1016 int hold_space_size = 0;
1019 pattern_space_size += strlen(pattern_space);
1021 hold_space_size = strlen(bbg.hold_space);
1022 pattern_space = xrealloc(pattern_space,
1023 pattern_space_size + hold_space_size);
1024 if (pattern_space_size == 2) pattern_space[0]=0;
1025 strcat(pattern_space, "\n");
1027 strcat(pattern_space, bbg.hold_space);
1032 case 'h': /* Replace hold space with pattern space */
1033 free(bbg.hold_space);
1034 bbg.hold_space = bb_xstrdup(pattern_space);
1036 case 'H': /* Append newline and pattern space to hold space */
1038 int hold_space_size = 2;
1039 int pattern_space_size = 0;
1042 hold_space_size += strlen(bbg.hold_space);
1044 pattern_space_size = strlen(pattern_space);
1045 bbg.hold_space = xrealloc(bbg.hold_space,
1046 hold_space_size + pattern_space_size);
1048 if (hold_space_size == 2) *bbg.hold_space=0;
1049 strcat(bbg.hold_space, "\n");
1050 if (pattern_space) strcat(bbg.hold_space, pattern_space);
1054 case 'x': /* Exchange hold and pattern space */
1056 char *tmp = pattern_space;
1057 pattern_space = bbg.hold_space;
1059 bbg.hold_space = tmp;
1067 * exit point from sedding...
1070 /* we will print the line unless we were told to be quiet ('-n')
1071 or if the line was suppressed (ala 'd'elete) */
1072 if (!bbg.be_quiet) sed_puts(pattern_space,no_newline);
1074 /* Delete and such jump here. */
1077 free(pattern_space);
1081 /* It is possible to have a command line argument with embedded
1082 newlines. This counts as multiple command lines. */
1084 static void add_cmd_block(char *cmdstr)
1087 char *temp=bb_xstrdup(cmdstr),*temp2=temp;
1090 int len=strcspn(temp2,"\n");
1091 if(!temp2[len]) go=0;
1099 int sed_main(int argc, char **argv)
1101 int status = EXIT_SUCCESS, opt, getpat = 1;
1103 bbg.sed_cmd_tail=&bbg.sed_cmd_head;
1105 /* destroy command strings on exit */
1106 if (ENABLE_FEATURE_CLEAN_UP) atexit(sed_free_and_close_stuff);
1108 /* Lie to autoconf when it starts asking stupid questions. */
1109 if(argc==2 && !strcmp(argv[1],"--version")) {
1110 printf("This is not GNU sed version 4.0\n");
1114 /* do normal option parsing */
1115 while ((opt = getopt(argc, argv, "irne:f:")) > 0) {
1119 atexit(cleanup_outname);
1122 bbg.regex_type|=REG_EXTENDED;
1128 add_cmd_block(optarg);
1136 cmdfile = bb_xfopen(optarg, "r");
1138 while ((line = bb_get_chomped_line_from_file(cmdfile)) != NULL) {
1143 bb_xprint_and_close_file(cmdfile);
1152 /* if we didn't get a pattern from -e or -f, use argv[optind] */
1154 if (argv[optind] == NULL)
1157 add_cmd_block(argv[optind++]);
1159 /* Flush any unfinished commands. */
1162 /* By default, we write to stdout */
1163 bbg.nonstdout=stdout;
1165 /* argv[(optind)..(argc-1)] should be names of file to process. If no
1166 * files were specified or '-' was specified, take input from stdin.
1167 * Otherwise, we process all the files specified. */
1168 if (argv[optind] == NULL) {
1169 if(bbg.in_place) bb_error_msg_and_die("Filename required for -i");
1170 add_input_file(stdin);
1176 for (i = optind; i < argc; i++) {
1177 if(!strcmp(argv[i], "-") && !bbg.in_place) {
1178 add_input_file(stdin);
1181 file = bb_wfopen(argv[i], "r");
1184 struct stat statbuf;
1187 bbg.outname=bb_xstrndup(argv[i],strlen(argv[i])+6);
1188 strcat(bbg.outname,"XXXXXX");
1189 if(-1==(nonstdoutfd=mkstemp(bbg.outname)))
1190 bb_error_msg_and_die("no temp file");
1191 bbg.nonstdout=fdopen(nonstdoutfd,"w");
1193 /* Set permissions of output file */
1195 fstat(fileno(file),&statbuf);
1196 fchmod(nonstdoutfd,statbuf.st_mode);
1197 add_input_file(file);
1199 fclose(bbg.nonstdout);
1201 bbg.nonstdout=stdout;
1203 rename(bbg.outname,argv[i]);
1206 } else add_input_file(file);
1208 status = EXIT_FAILURE;
1212 if(bbg.input_file_count>bbg.current_input_file) process_files();