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 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
29 Files are laid out to avoid unnecessary function declarations. So for
30 example, every function add_cmd calls occurs before add_cmd in this file.
32 add_cmd() is called on each line of sed command text (from a file or from
33 the command line). It calls get_address() and parse_cmd_args(). The
34 resulting sed_cmd_t structures are appended to a linked list
35 (sed_cmd_head/sed_cmd_tail).
37 process_file() does actual sedding, reading data lines from an input FILE *
38 (which could be stdin) and applying the sed command list (sed_cmd_head) to
39 each of the resulting lines.
41 sed_main() is where external code calls into this, with a command line.
46 Supported features and commands in this version of sed:
49 - address matching: num|/matchstr/[,num|/matchstr/|$]command
50 - commands: (p)rint, (d)elete, (s)ubstitue (with g & I flags)
51 - edit commands: (a)ppend, (i)nsert, (c)hange
52 - file commands: (r)ead
53 - backreferences in substitution expressions (\1, \2...\9)
54 - grouped commands: {cmd1;cmd2}
55 - transliteration (y/source-chars/dest-chars/)
56 - pattern space hold space storing / swapping (g, h, x)
57 - labels / branching (: label, b, t)
59 (Note: Specifying an address (range) to match is *optional*; commands
60 default to the whole pattern space if no specific address match was
70 - Create a wrapper around regex to make libc's regex conform with sed
74 Reference http://www.opengroup.org/onlinepubs/007904975/utilities/sed.html
78 #include <unistd.h> /* for getopt() */
80 #include <string.h> /* for strdup() */
82 #include <ctype.h> /* for isspace() */
86 typedef struct sed_cmd_s {
87 /* Ordered by alignment requirements: currently 36 bytes on x86 */
90 regex_t *beg_match; /* sed -e '/match/cmd' */
91 regex_t *end_match; /* sed -e '/match/,/end_match/cmd' */
92 regex_t *sub_match; /* For 's/sub_match/string/' */
93 int beg_line; /* 'sed 1p' 0 == apply commands to all lines */
94 int end_line; /* 'sed 1,3p' 0 == one line only. -1 = last line ($) */
96 FILE *file; /* File (sr) command writes to, -1 for none. */
97 char *string; /* Data string for (saicytb) commands. */
99 unsigned short which_match; /* (s) Which match to replace (0 for all) */
101 /* Bitfields (gcc won't group them if we don't) */
102 unsigned int invert:1; /* the '!' after the address */
103 unsigned int in_match:1; /* Next line also included in match? */
104 unsigned int no_newline:1; /* Last line written by (sr) had no '\n' */
105 unsigned int sub_p:1; /* (s) print option */
109 char cmd; /* The command char: abcdDgGhHilnNpPqrstwxy:={} */
110 struct sed_cmd_s *next; /* Next command (linked list, NULL terminated) */
115 static int be_quiet = 0, in_place=0, regex_type=0;
120 static const char bad_format_in_subst[] =
121 "bad format in substitution expression";
122 const char *const semicolon_whitespace = "; \n\r\t\v";
124 regmatch_t regmatch[10];
125 static regex_t *previous_regex_ptr = NULL;
127 /* linked list of sed commands */
128 static sed_cmd_t sed_cmd_head;
129 static sed_cmd_t *sed_cmd_tail = &sed_cmd_head;
131 /* Linked list of append lines */
134 struct append_list *next;
136 struct append_list *append_head=NULL, *append_tail=NULL;
138 #ifdef CONFIG_FEATURE_CLEAN_UP
139 static void free_and_close_stuff(void)
141 sed_cmd_t *sed_cmd = sed_cmd_head.next;
144 append_tail=append_head->next;
145 free(append_head->string);
147 append_head=append_tail;
151 sed_cmd_t *sed_cmd_next = sed_cmd->next;
154 bb_xprint_and_close_file(sed_cmd->file);
156 if (sed_cmd->beg_match) {
157 regfree(sed_cmd->beg_match);
158 free(sed_cmd->beg_match);
160 if (sed_cmd->end_match) {
161 regfree(sed_cmd->end_match);
162 free(sed_cmd->end_match);
164 if (sed_cmd->sub_match) {
165 regfree(sed_cmd->sub_match);
166 free(sed_cmd->sub_match);
168 free(sed_cmd->string);
170 sed_cmd = sed_cmd_next;
175 /* If something bad happens during -i operation, delete temp file */
177 static void cleanup_outname(void)
179 if(outname) unlink(outname);
182 /* strdup, replacing "\n" with '\n', and "\delimiter" with 'delimiter' */
184 static void parse_escapes(char *dest, const char *string, int len, char from, char to)
189 if(string[i] == '\\') {
190 if(!to || string[i+1] == from) {
191 *(dest++) = to ? to : string[i+1];
194 } else *(dest++)=string[i++];
196 *(dest++) = string[i++];
201 static char *copy_parsing_slashn(const char *string, int len)
203 char *dest=xmalloc(len+1);
205 parse_escapes(dest,string,len,'n','\n');
211 * index_of_next_unescaped_regexp_delim - walks left to right through a string
212 * beginning at a specified index and returns the index of the next regular
213 * expression delimiter (typically a forward * slash ('/')) not preceded by
216 static int index_of_next_unescaped_regexp_delim(const char delimiter,
224 for (; (ch = str[idx]); idx++) {
226 if (ch == ']' && !(bracket == idx - 1 || (bracket == idx - 2
227 && str[idx - 1] == '^')))
235 else if (ch == delimiter)
239 /* if we make it to here, we've hit the end of the string */
244 * Returns the index of the third delimiter
246 static int parse_regex_delim(const char *cmdstr, char **match, char **replace)
248 const char *cmdstr_ptr = cmdstr;
252 /* verify that the 's' or 'y' is followed by something. That something
253 * (typically a 'slash') is now our regexp delimiter... */
254 if (*cmdstr == '\0') bb_error_msg_and_die(bad_format_in_subst);
255 delimiter = *(cmdstr_ptr++);
257 /* save the match string */
258 idx = index_of_next_unescaped_regexp_delim(delimiter, cmdstr_ptr);
260 bb_error_msg_and_die(bad_format_in_subst);
262 *match = copy_parsing_slashn(cmdstr_ptr, idx);
264 /* save the replacement string */
265 cmdstr_ptr += idx + 1;
266 idx = index_of_next_unescaped_regexp_delim(delimiter, cmdstr_ptr);
268 bb_error_msg_and_die(bad_format_in_subst);
270 *replace = copy_parsing_slashn(cmdstr_ptr, idx);
272 return ((cmdstr_ptr - cmdstr) + idx);
276 * returns the index in the string just past where the address ends.
278 static int get_address(char *my_str, int *linenum, regex_t ** regex)
282 if (isdigit(*my_str)) {
283 *linenum = strtol(my_str, &pos, 10);
284 /* endstr shouldnt ever equal NULL */
285 } else if (*my_str == '$') {
288 } else if (*my_str == '/' || *my_str == '\\') {
293 if (*my_str == '\\') delimiter = *(++pos);
294 else delimiter = '/';
295 next = index_of_next_unescaped_regexp_delim(delimiter, ++pos);
297 bb_error_msg_and_die("unterminated match expression");
299 temp=copy_parsing_slashn(pos,next);
300 *regex = (regex_t *) xmalloc(sizeof(regex_t));
301 xregcomp(*regex, temp, regex_type|REG_NEWLINE);
303 /* Move position to next character after last delimiter */
309 /* Grab a filename. Whitespace at start is skipped, then goes to EOL. */
310 static int parse_file_cmd(sed_cmd_t * sed_cmd, const char *filecmdstr, char **retval)
312 int start = 0, idx, hack=0;
314 /* Skip whitespace, then grab filename to end of line */
315 while (isspace(filecmdstr[start])) start++;
317 while(filecmdstr[idx] && filecmdstr[idx]!='\n') idx++;
318 /* If lines glued together, put backslash back. */
319 if(filecmdstr[idx]=='\n') hack=1;
320 if(idx==start) bb_error_msg_and_die("Empty filename");
321 *retval = bb_xstrndup(filecmdstr+start, idx-start+hack+1);
322 if(hack) *(idx+*retval)='\\';
327 static int parse_subst_cmd(sed_cmd_t * const sed_cmd, char *substr)
329 int cflags = regex_type;
334 * A substitution command should look something like this:
335 * s/match/replace/ #gIpw
339 idx = parse_regex_delim(substr, &match, &sed_cmd->string);
341 /* determine the number of back references in the match string */
342 /* Note: we compute this here rather than in the do_subst_command()
343 * function to save processor time, at the expense of a little more memory
344 * (4 bits) per sed_cmd */
346 /* process the flags */
348 sed_cmd->which_match=1;
349 while (substr[++idx]) {
350 /* Parse match number */
351 if(isdigit(substr[idx])) {
353 /* Match 0 treated as all, multiple matches we take the last one. */
354 char *pos=substr+idx;
355 sed_cmd->which_match=(unsigned short)strtol(substr+idx,&pos,10);
361 if(isspace(substr[idx])) continue;
363 switch (substr[idx]) {
364 /* Replace all occurrences */
366 if (match[0] != '^') sed_cmd->which_match = 0;
368 /* Print pattern space */
375 idx+=parse_file_cmd(sed_cmd,substr+idx,&temp);
379 /* Ignore case (gnu exension) */
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(":bt", sed_cmd->cmd)) {
435 while(isspace(*cmdstr)) cmdstr++;
436 length = strcspn(cmdstr, semicolon_whitespace);
438 sed_cmd->string = strndup(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 void add_cmd(char *cmdstr)
476 static char *add_cmd_line=NULL;
480 /* Append this line to any unfinished line from last time. */
482 int lastlen=strlen(add_cmd_line);
483 char *tmp=xmalloc(lastlen+strlen(cmdstr)+2);
485 memcpy(tmp,add_cmd_line,lastlen);
487 strcpy(tmp+lastlen+1,cmdstr);
489 cmdstr=add_cmd_line=tmp;
490 } else add_cmd_line=NULL;
492 /* If this line ends with backslash, request next line. */
494 if(temp && cmdstr[temp-1]=='\\') {
495 if(!add_cmd_line) add_cmd_line=strdup(cmdstr);
496 add_cmd_line[temp-1]=0;
500 /* Loop parsing all commands in this line. */
502 /* Skip leading whitespace and semicolons */
503 cmdstr += strspn(cmdstr, semicolon_whitespace);
505 /* If no more commands, exit. */
508 /* if this is a comment, jump past it and keep going */
509 if (*cmdstr == '#') {
510 /* "#n" is the same as using -n on the command line */
511 if (cmdstr[1] == 'n') be_quiet++;
512 if(!(cmdstr=strpbrk(cmdstr, "\n\r"))) break;
517 * format is: [addr][,addr][!]cmd
522 sed_cmd = xcalloc(1, sizeof(sed_cmd_t));
524 /* first part (if present) is an address: either a '$', a number or a /regex/ */
525 cmdstr += get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
527 /* second part (if present) will begin with a comma */
528 if (*cmdstr == ',') {
532 idx = get_address(cmdstr, &sed_cmd->end_line, &sed_cmd->end_match);
533 if (!idx) bb_error_msg_and_die("get_address: no address found in string\n");
537 /* skip whitespace before the command */
538 while (isspace(*cmdstr)) cmdstr++;
540 /* Check for inversion flag */
541 if (*cmdstr == '!') {
545 /* skip whitespace before the command */
546 while (isspace(*cmdstr)) cmdstr++;
549 /* last part (mandatory) will be a command */
550 if (!*cmdstr) bb_error_msg_and_die("missing command");
551 sed_cmd->cmd = *(cmdstr++);
552 cmdstr = parse_cmd_args(sed_cmd, cmdstr);
554 /* Add the command to the command array */
555 sed_cmd_tail->next = sed_cmd;
556 sed_cmd_tail = sed_cmd_tail->next;
559 /* If we glued multiple lines together, free the memory. */
567 char *buf; /* Space to hold string */
568 int idx; /* Space used */
569 int len; /* Space allocated */
574 void pipe_putc(char c)
576 if(pipeline.idx==pipeline.len) {
577 pipeline.buf = xrealloc(pipeline.buf, pipeline.len + PIPE_GROW);
578 pipeline.len+=PIPE_GROW;
580 pipeline.buf[pipeline.idx++] = (c);
583 static void do_subst_w_backrefs(const char *line, const char *replace)
587 /* go through the replacement string */
588 for (i = 0; replace[i]; i++) {
589 /* if we find a backreference (\1, \2, etc.) print the backref'ed * text */
590 if (replace[i] == '\\' && replace[i+1]>'0' && replace[i+1]<='9') {
591 int backref=replace[++i]-'0';
593 /* print out the text held in regmatch[backref] */
594 if(regmatch[backref].rm_so != -1)
595 for (j = regmatch[backref].rm_so; j < regmatch[backref].rm_eo; j++)
599 /* if we find a backslash escaped character, print the character */
600 else if (replace[i] == '\\') pipe_putc(replace[++i]);
602 /* if we find an unescaped '&' print out the whole matched text. */
603 else if (replace[i] == '&')
604 for (j = regmatch[0].rm_so; j < regmatch[0].rm_eo; j++)
606 /* Otherwise just output the character. */
607 else pipe_putc(replace[i]);
611 static int do_subst_command(sed_cmd_t * sed_cmd, char **line)
613 char *oldline = *line;
616 regex_t *current_regex;
618 /* Handle empty regex. */
619 if (sed_cmd->sub_match == NULL) {
620 current_regex = previous_regex_ptr;
622 bb_error_msg_and_die("No previous regexp.");
623 } else previous_regex_ptr = current_regex = sed_cmd->sub_match;
625 /* Find the first match */
626 if(REG_NOMATCH==regexec(current_regex, oldline, 10, regmatch, 0))
629 /* Initialize temporary output buffer. */
630 pipeline.buf=xmalloc(PIPE_GROW);
631 pipeline.len=PIPE_GROW;
634 /* Now loop through, substituting for matches */
638 /* Work around bug in glibc regexec, demonstrated by:
639 echo " a.b" | busybox sed 's [^ .]* x g'
640 The match_count check is so not to break
641 echo "hi" | busybox sed 's/^/!/g' */
642 if(!regmatch[0].rm_so && !regmatch[0].rm_eo && match_count) {
643 pipe_putc(*(oldline++));
649 /* If we aren't interested in this match, output old line to
650 end of match and continue */
651 if(sed_cmd->which_match && sed_cmd->which_match!=match_count) {
652 for(i=0;i<regmatch[0].rm_eo;i++)
653 pipe_putc(oldline[i]);
657 /* print everything before the match */
658 for (i = 0; i < regmatch[0].rm_so; i++) pipe_putc(oldline[i]);
660 /* then print the substitution string */
661 do_subst_w_backrefs(oldline, sed_cmd->string);
663 /* advance past the match */
664 oldline += regmatch[0].rm_eo;
665 /* flag that something has changed */
668 /* if we're not doing this globally, get out now */
669 if (sed_cmd->which_match) break;
670 } while (*oldline && (regexec(current_regex, oldline, 10, regmatch, 0) != REG_NOMATCH));
672 /* Copy rest of string into output pipeline */
674 while(*oldline) pipe_putc(*(oldline++));
678 *line = pipeline.buf;
682 /* Set command pointer to point to this label. (Does not handle null label.) */
683 static sed_cmd_t *branch_to(const char *label)
687 for (sed_cmd = sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
688 if ((sed_cmd->cmd == ':') && (sed_cmd->string) && (strcmp(sed_cmd->string, label) == 0)) {
692 bb_error_msg_and_die("Can't find label for jump to `%s'", label);
695 /* Append copy of string to append buffer */
696 static void append(char *s)
698 struct append_list *temp=calloc(1,sizeof(struct append_list));
701 append_tail=(append_tail->next=temp);
702 else append_head=append_tail=temp;
703 temp->string=strdup(s);
706 static void flush_append(void)
708 /* Output appended lines. */
710 fprintf(nonstdout,"%s\n",append_head->string);
711 append_tail=append_head->next;
712 free(append_head->string);
714 append_head=append_tail;
716 append_head=append_tail=NULL;
719 /* Get next line of input, flushing append buffer and noting if we hit EOF
720 * without a newline on the last line.
722 static char *get_next_line(FILE * file, int *no_newline)
728 temp=bb_get_line_from_file(file);
731 if(len && temp[len-1]=='\n') temp[len-1]=0;
738 /* Output line of text. missing_newline means the last line output did not
739 end with a newline. no_newline means this line does not end with a
742 static int puts_maybe_newline(char *s, FILE *file, int missing_newline, int no_newline)
744 if(missing_newline) fputc('\n',file);
746 if(!no_newline) fputc('\n',file);
749 fprintf(stderr,"Write failed.\n");
750 exit(4); /* It's what gnu sed exits with... */
756 #define sed_puts(s,n) missing_newline=puts_maybe_newline(s,nonstdout,missing_newline,n)
758 static void process_file(FILE *file)
760 char *pattern_space, *next_line, *hold_space=NULL;
761 static int linenum = 0, missing_newline=0;
762 int no_newline,next_no_newline=0;
764 next_line = get_next_line(file,&next_no_newline);
766 /* go through every line in the file */
771 /* Advance to next line. Stop if out of lines. */
772 if(!(pattern_space=next_line)) break;
773 no_newline=next_no_newline;
775 /* Read one line in advance so we can act on the last line, the '$' address */
776 next_line = get_next_line(file,&next_no_newline);
779 /* for every line, go through all the commands */
780 for (sed_cmd = sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
781 int old_matched, matched;
783 old_matched = sed_cmd->in_match;
785 /* Determine if this command matches this line: */
787 /* Are we continuing a previous multi-line match? */
789 sed_cmd->in_match = sed_cmd->in_match
791 /* Or is no range necessary? */
792 || (!sed_cmd->beg_line && !sed_cmd->end_line
793 && !sed_cmd->beg_match && !sed_cmd->end_match)
795 /* Or did we match the start of a numerical range? */
796 || (sed_cmd->beg_line > 0 && (sed_cmd->beg_line == linenum))
798 /* Or does this line match our begin address regex? */
799 || (sed_cmd->beg_match &&
800 !regexec(sed_cmd->beg_match, pattern_space, 0, NULL, 0))
802 /* Or did we match last line of input? */
803 || (sed_cmd->beg_line == -1 && next_line == NULL);
805 /* Snapshot the value */
807 matched = sed_cmd->in_match;
809 /* Is this line the end of the current match? */
812 sed_cmd->in_match = !(
813 /* has the ending line come, or is this a single address command? */
815 sed_cmd->end_line==-1 ?
817 : sed_cmd->end_line<=linenum
818 : !sed_cmd->end_match)
819 /* or does this line matches our last address regex */
820 || (sed_cmd->end_match && old_matched && (regexec(sed_cmd->end_match, pattern_space, 0, NULL, 0) == 0))
824 /* Skip blocks of commands we didn't match. */
825 if (sed_cmd->cmd == '{') {
826 if(sed_cmd->invert ? matched : !matched)
827 while(sed_cmd && sed_cmd->cmd!='}') sed_cmd=sed_cmd->next;
828 if(!sed_cmd) bb_error_msg_and_die("Unterminated {");
832 /* Okay, so did this line match? */
833 if (sed_cmd->invert ? !matched : matched) {
834 /* Update last used regex in case a blank substitute BRE is found */
835 if (sed_cmd->beg_match) {
836 previous_regex_ptr = sed_cmd->beg_match;
840 switch (sed_cmd->cmd) {
842 /* Print line number */
844 fprintf(nonstdout,"%d\n", linenum);
847 /* Write the current pattern space up to the first newline */
850 char *tmp = strchr(pattern_space, '\n');
854 sed_puts(pattern_space,1);
861 /* Write the current pattern space to output */
863 sed_puts(pattern_space,no_newline);
865 /* Delete up through first newline */
868 char *tmp = strchr(pattern_space,'\n');
871 tmp=bb_xstrdup(tmp+1);
877 /* discard this line. */
881 /* Substitute with regex */
883 if(do_subst_command(sed_cmd, &pattern_space)) {
886 /* handle p option */
888 sed_puts(pattern_space,no_newline);
889 /* handle w option */
891 sed_cmd->no_newline=puts_maybe_newline(pattern_space, sed_cmd->file, sed_cmd->no_newline, no_newline);
896 /* Append line to linked list to be printed later */
899 append(sed_cmd->string);
903 /* Insert text before this line */
905 sed_puts(sed_cmd->string,1);
908 /* Cut and paste text (replace) */
910 /* Only triggers on last line of a matching range. */
911 if (!sed_cmd->in_match) sed_puts(sed_cmd->string,1);
914 /* Read file, append contents to output */
919 outfile = fopen(sed_cmd->string, "r");
923 while ((line = bb_get_chomped_line_from_file(outfile))
926 bb_xprint_and_close_file(outfile);
932 /* Write pattern space to file. */
934 sed_cmd->no_newline=puts_maybe_newline(pattern_space,sed_cmd->file, sed_cmd->no_newline,no_newline);
937 /* Read next line from input */
940 sed_puts(pattern_space,no_newline);
943 pattern_space = next_line;
944 no_newline=next_no_newline;
945 next_line = get_next_line(file,&next_no_newline);
951 /* Quit. End of script, end of input. */
953 /* Exit the outer while loop */
956 goto discard_commands;
958 /* Append the next line to the current line */
961 /* If no next line, jump to end of script and exit. */
962 if (next_line == NULL) {
963 /* Jump to end of script and exit */
967 /* append next_line, read new next_line. */
969 int len=strlen(pattern_space);
971 pattern_space = realloc(pattern_space, len + strlen(next_line) + 2);
972 pattern_space[len]='\n';
973 strcpy(pattern_space+len+1, next_line);
974 no_newline=next_no_newline;
975 next_line = get_next_line(file,&next_no_newline);
981 /* Test if substition worked, branch if so. */
983 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];
1008 case 'g': /* Replace pattern space with hold space */
1009 free(pattern_space);
1011 pattern_space = strdup(hold_space);
1015 case 'G': /* Append newline and hold space to pattern space */
1017 int pattern_space_size = 2;
1018 int hold_space_size = 0;
1021 pattern_space_size += strlen(pattern_space);
1022 if (hold_space) hold_space_size = strlen(hold_space);
1023 pattern_space = xrealloc(pattern_space, pattern_space_size + hold_space_size);
1024 if (pattern_space_size == 2) pattern_space[0]=0;
1025 strcat(pattern_space, "\n");
1026 if (hold_space) strcat(pattern_space, hold_space);
1031 case 'h': /* Replace hold space with pattern space */
1033 hold_space = strdup(pattern_space);
1035 case 'H': /* Append newline and pattern space to hold space */
1037 int hold_space_size = 2;
1038 int pattern_space_size = 0;
1040 if (hold_space) hold_space_size += strlen(hold_space);
1042 pattern_space_size = strlen(pattern_space);
1043 hold_space = xrealloc(hold_space,
1044 hold_space_size + pattern_space_size);
1046 if (hold_space_size == 2) hold_space[0]=0;
1047 strcat(hold_space, "\n");
1048 if (pattern_space) strcat(hold_space, pattern_space);
1052 case 'x': /* Exchange hold and pattern space */
1054 char *tmp = pattern_space;
1055 pattern_space = hold_space;
1065 * exit point from sedding...
1068 /* we will print the line unless we were told to be quiet ('-n')
1069 or if the line was suppressed (ala 'd'elete) */
1070 if (!be_quiet) sed_puts(pattern_space,no_newline);
1072 /* Delete and such jump here. */
1075 free(pattern_space);
1079 /* It is possible to have a command line argument with embedded
1080 newlines. This counts as multiple command lines. */
1082 static void add_cmd_block(char *cmdstr)
1085 char *temp=bb_xstrdup(cmdstr),*temp2=temp;
1088 int len=strcspn(temp2,"\n");
1089 if(!temp2[len]) go=0;
1097 extern int sed_main(int argc, char **argv)
1099 int status = EXIT_SUCCESS;
1103 #ifdef CONFIG_FEATURE_CLEAN_UP
1104 /* destroy command strings on exit */
1105 if (atexit(free_and_close_stuff) == -1)
1106 bb_perror_msg_and_die("atexit");
1109 #define LIE_TO_AUTOCONF
1110 #ifdef LIE_TO_AUTOCONF
1111 if(argc==2 && !strcmp(argv[1],"--version")) {
1112 printf("This is not GNU sed version 4.0\n");
1117 /* do normal option parsing */
1118 while ((opt = getopt(argc, argv, "irne:f:")) > 0) {
1122 atexit(cleanup_outname);
1125 regex_type|=REG_EXTENDED;
1131 add_cmd_block(optarg);
1139 cmdfile = bb_xfopen(optarg, "r");
1141 while ((line = bb_get_chomped_line_from_file(cmdfile))
1147 bb_xprint_and_close_file(cmdfile);
1156 /* if we didn't get a pattern from a -e and no command file was specified,
1157 * argv[optind] should be the pattern. no pattern, no worky */
1159 if (argv[optind] == NULL)
1162 add_cmd_block(argv[optind++]);
1164 /* Flush any unfinished commands. */
1167 /* By default, we write to stdout */
1170 /* argv[(optind)..(argc-1)] should be names of file to process. If no
1171 * files were specified or '-' was specified, take input from stdin.
1172 * Otherwise, we process all the files specified. */
1173 if (argv[optind] == NULL) {
1175 fprintf(stderr,"sed: Filename required for -i\n");
1178 process_file(stdin);
1183 for (i = optind; i < argc; i++) {
1184 if(!strcmp(argv[i], "-") && !in_place) {
1185 process_file(stdin);
1187 file = bb_wfopen(argv[i], "r");
1190 struct stat statbuf;
1191 outname=bb_xstrndup(argv[i],strlen(argv[i])+6);
1192 strcat(outname,"XXXXXX");
1193 /* Set permissions of output file */
1194 fstat(fileno(file),&statbuf);
1196 nonstdout=bb_wfopen(outname,"w");
1197 /* Set permissions of output file */
1198 fstat(fileno(file),&statbuf);
1199 fchmod(fileno(nonstdout),statbuf.st_mode);
1200 atexit(cleanup_outname);
1208 rename(outname,argv[i]);
1213 status = EXIT_FAILURE;