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 add_input_file() adds a FILE * to the list of input files. We need to
38 know them all ahead of time to find the last line for the $ match.
40 process_files() does actual sedding, reading data lines from each input FILE *
41 (which could be stdin) and applying the sed command list (sed_cmd_head) to
42 each of the resulting lines.
44 sed_main() is where external code calls into this, with a command line.
49 Supported features and commands in this version of sed:
52 - address matching: num|/matchstr/[,num|/matchstr/|$]command
53 - commands: (p)rint, (d)elete, (s)ubstitue (with g & I flags)
54 - edit commands: (a)ppend, (i)nsert, (c)hange
55 - file commands: (r)ead
56 - backreferences in substitution expressions (\1, \2...\9)
57 - grouped commands: {cmd1;cmd2}
58 - transliteration (y/source-chars/dest-chars/)
59 - pattern space hold space storing / swapping (g, h, x)
60 - labels / branching (: label, b, t, T)
62 (Note: Specifying an address (range) to match is *optional*; commands
63 default to the whole pattern space if no specific address match was
73 - Create a wrapper around regex to make libc's regex conform with sed
77 Reference http://www.opengroup.org/onlinepubs/007904975/utilities/sed.html
81 #include <unistd.h> /* for getopt() */
83 #include <string.h> /* for strdup() */
85 #include <ctype.h> /* for isspace() */
89 typedef struct sed_cmd_s {
90 /* Ordered by alignment requirements: currently 36 bytes on x86 */
93 regex_t *beg_match; /* sed -e '/match/cmd' */
94 regex_t *end_match; /* sed -e '/match/,/end_match/cmd' */
95 regex_t *sub_match; /* For 's/sub_match/string/' */
96 int beg_line; /* 'sed 1p' 0 == apply commands to all lines */
97 int end_line; /* 'sed 1,3p' 0 == one line only. -1 = last line ($) */
99 FILE *file; /* File (sr) command writes to, -1 for none. */
100 char *string; /* Data string for (saicytb) commands. */
102 unsigned short which_match; /* (s) Which match to replace (0 for all) */
104 /* Bitfields (gcc won't group them if we don't) */
105 unsigned int invert:1; /* the '!' after the address */
106 unsigned int in_match:1; /* Next line also included in match? */
107 unsigned int no_newline:1; /* Last line written by (sr) had no '\n' */
108 unsigned int sub_p:1; /* (s) print option */
112 char cmd; /* The command char: abcdDgGhHilnNpPqrstwxy:={} */
113 struct sed_cmd_s *next; /* Next command (linked list, NULL terminated) */
118 static int be_quiet, in_place, regex_type;
119 static FILE *nonstdout;
120 static char *outname,*hold_space;
122 /* List of input files */
123 static int input_file_count,current_input_file;
124 static FILE **input_file_list;
126 static const char bad_format_in_subst[] =
127 "bad format in substitution expression";
128 static const char *const semicolon_whitespace = "; \n\r\t\v";
130 static regmatch_t regmatch[10];
131 static regex_t *previous_regex_ptr;
133 /* linked list of sed commands */
134 static sed_cmd_t sed_cmd_head;
135 static sed_cmd_t *sed_cmd_tail = &sed_cmd_head;
137 /* Linked list of append lines */
140 struct append_list *next;
142 static struct append_list *append_head=NULL, *append_tail=NULL;
144 #ifdef CONFIG_FEATURE_CLEAN_UP
145 static void free_and_close_stuff(void)
147 sed_cmd_t *sed_cmd = sed_cmd_head.next;
150 append_tail=append_head->next;
151 free(append_head->string);
153 append_head=append_tail;
157 sed_cmd_t *sed_cmd_next = sed_cmd->next;
160 bb_xprint_and_close_file(sed_cmd->file);
162 if (sed_cmd->beg_match) {
163 regfree(sed_cmd->beg_match);
164 free(sed_cmd->beg_match);
166 if (sed_cmd->end_match) {
167 regfree(sed_cmd->end_match);
168 free(sed_cmd->end_match);
170 if (sed_cmd->sub_match) {
171 regfree(sed_cmd->sub_match);
172 free(sed_cmd->sub_match);
174 free(sed_cmd->string);
176 sed_cmd = sed_cmd_next;
179 if(hold_space) free(hold_space);
181 while(current_input_file<input_file_count)
182 fclose(input_file_list[current_input_file++]);
186 /* If something bad happens during -i operation, delete temp file */
188 static void cleanup_outname(void)
190 if(outname) unlink(outname);
193 /* strdup, replacing "\n" with '\n', and "\delimiter" with 'delimiter' */
195 static void parse_escapes(char *dest, const char *string, int len, char from, char to)
200 if(string[i] == '\\') {
201 if(!to || string[i+1] == from) {
202 *(dest++) = to ? to : string[i+1];
205 } else *(dest++)=string[i++];
207 *(dest++) = string[i++];
212 static char *copy_parsing_slashn(const char *string, int len)
214 char *dest=xmalloc(len+1);
216 parse_escapes(dest,string,len,'n','\n');
222 * index_of_next_unescaped_regexp_delim - walks left to right through a string
223 * beginning at a specified index and returns the index of the next regular
224 * expression delimiter (typically a forward * slash ('/')) not preceded by
227 static int index_of_next_unescaped_regexp_delim(const char delimiter,
235 for (; (ch = str[idx]); idx++) {
237 if (ch == ']' && !(bracket == idx - 1 || (bracket == idx - 2
238 && str[idx - 1] == '^')))
246 else if (ch == delimiter)
250 /* if we make it to here, we've hit the end of the string */
255 * Returns the index of the third delimiter
257 static int parse_regex_delim(const char *cmdstr, char **match, char **replace)
259 const char *cmdstr_ptr = cmdstr;
263 /* verify that the 's' or 'y' is followed by something. That something
264 * (typically a 'slash') is now our regexp delimiter... */
265 if (*cmdstr == '\0') bb_error_msg_and_die(bad_format_in_subst);
266 delimiter = *(cmdstr_ptr++);
268 /* save the match string */
269 idx = index_of_next_unescaped_regexp_delim(delimiter, cmdstr_ptr);
271 bb_error_msg_and_die(bad_format_in_subst);
273 *match = copy_parsing_slashn(cmdstr_ptr, idx);
275 /* save the replacement string */
276 cmdstr_ptr += idx + 1;
277 idx = index_of_next_unescaped_regexp_delim(delimiter, cmdstr_ptr);
279 bb_error_msg_and_die(bad_format_in_subst);
281 *replace = copy_parsing_slashn(cmdstr_ptr, idx);
283 return ((cmdstr_ptr - cmdstr) + idx);
287 * returns the index in the string just past where the address ends.
289 static int get_address(char *my_str, int *linenum, regex_t ** regex)
293 if (isdigit(*my_str)) {
294 *linenum = strtol(my_str, &pos, 10);
295 /* endstr shouldnt ever equal NULL */
296 } else if (*my_str == '$') {
299 } else if (*my_str == '/' || *my_str == '\\') {
304 if (*my_str == '\\') delimiter = *(++pos);
305 else delimiter = '/';
306 next = index_of_next_unescaped_regexp_delim(delimiter, ++pos);
308 bb_error_msg_and_die("unterminated match expression");
310 temp=copy_parsing_slashn(pos,next);
311 *regex = (regex_t *) xmalloc(sizeof(regex_t));
312 xregcomp(*regex, temp, regex_type|REG_NEWLINE);
314 /* Move position to next character after last delimiter */
320 /* Grab a filename. Whitespace at start is skipped, then goes to EOL. */
321 static int parse_file_cmd(sed_cmd_t * sed_cmd, const char *filecmdstr, char **retval)
323 int start = 0, idx, hack=0;
325 /* Skip whitespace, then grab filename to end of line */
326 while (isspace(filecmdstr[start])) start++;
328 while(filecmdstr[idx] && filecmdstr[idx]!='\n') idx++;
329 /* If lines glued together, put backslash back. */
330 if(filecmdstr[idx]=='\n') hack=1;
331 if(idx==start) bb_error_msg_and_die("Empty filename");
332 *retval = bb_xstrndup(filecmdstr+start, idx-start+hack+1);
333 if(hack) *(idx+*retval)='\\';
338 static int parse_subst_cmd(sed_cmd_t * const sed_cmd, char *substr)
340 int cflags = regex_type;
345 * A substitution command should look something like this:
346 * s/match/replace/ #gIpw
350 idx = parse_regex_delim(substr, &match, &sed_cmd->string);
352 /* determine the number of back references in the match string */
353 /* Note: we compute this here rather than in the do_subst_command()
354 * function to save processor time, at the expense of a little more memory
355 * (4 bits) per sed_cmd */
357 /* process the flags */
359 sed_cmd->which_match=1;
360 while (substr[++idx]) {
361 /* Parse match number */
362 if(isdigit(substr[idx])) {
364 /* Match 0 treated as all, multiple matches we take the last one. */
365 char *pos=substr+idx;
366 sed_cmd->which_match=(unsigned short)strtol(substr+idx,&pos,10);
372 if(isspace(substr[idx])) continue;
374 switch (substr[idx]) {
375 /* Replace all occurrences */
377 if (match[0] != '^') sed_cmd->which_match = 0;
379 /* Print pattern space */
386 idx+=parse_file_cmd(sed_cmd,substr+idx,&temp);
390 /* Ignore case (gnu exension) */
398 bb_error_msg_and_die("bad option in substitution expression");
402 /* compile the match string into a regex */
403 if (*match != '\0') {
404 /* If match is empty, we use last regex used at runtime */
405 sed_cmd->sub_match = (regex_t *) xmalloc(sizeof(regex_t));
406 xregcomp(sed_cmd->sub_match, match, cflags);
414 * Process the commands arguments
416 static char *parse_cmd_args(sed_cmd_t *sed_cmd, char *cmdstr)
418 /* handle (s)ubstitution command */
419 if (sed_cmd->cmd == 's') cmdstr += parse_subst_cmd(sed_cmd, cmdstr);
420 /* handle edit cmds: (a)ppend, (i)nsert, and (c)hange */
421 else if (strchr("aic", sed_cmd->cmd)) {
422 if ((sed_cmd->end_line || sed_cmd->end_match) && sed_cmd->cmd != 'c')
424 ("only a beginning address can be specified for edit commands");
426 if(*cmdstr=='\n' || *cmdstr=='\\') {
429 } else if(isspace(*cmdstr)) cmdstr++;
432 sed_cmd->string = bb_xstrdup(cmdstr);
433 parse_escapes(sed_cmd->string,sed_cmd->string,strlen(cmdstr),0,0);
434 cmdstr += strlen(cmdstr);
435 /* handle file cmds: (r)ead */
436 } else if(strchr("rw", sed_cmd->cmd)) {
437 if (sed_cmd->end_line || sed_cmd->end_match)
438 bb_error_msg_and_die("Command only uses one address");
439 cmdstr += parse_file_cmd(sed_cmd, cmdstr, &sed_cmd->string);
440 if(sed_cmd->cmd=='w')
441 sed_cmd->file=bb_xfopen(sed_cmd->string,"w");
442 /* handle branch commands */
443 } else if (strchr(":btT", sed_cmd->cmd)) {
446 while(isspace(*cmdstr)) cmdstr++;
447 length = strcspn(cmdstr, semicolon_whitespace);
449 sed_cmd->string = strndup(cmdstr, length);
453 /* translation command */
454 else if (sed_cmd->cmd == 'y') {
455 char *match, *replace;
458 cmdstr+=parse_regex_delim(cmdstr, &match, &replace)+1;
459 /* \n already parsed, but \delimiter needs unescaping. */
460 parse_escapes(match,match,strlen(match),i,i);
461 parse_escapes(replace,replace,strlen(replace),i,i);
463 sed_cmd->string = xcalloc(1, (strlen(match) + 1) * 2);
464 for (i = 0; match[i] && replace[i]; i++) {
465 sed_cmd->string[i * 2] = match[i];
466 sed_cmd->string[(i * 2) + 1] = replace[i];
471 /* if it wasnt a single-letter command that takes no arguments
472 * then it must be an invalid command.
474 else if (strchr("dDgGhHlnNpPqx={}", sed_cmd->cmd) == 0) {
475 bb_error_msg_and_die("Unsupported command %c", sed_cmd->cmd);
478 /* give back whatever's left over */
483 /* Parse address+command sets, skipping comment lines. */
485 static void add_cmd(char *cmdstr)
487 static char *add_cmd_line=NULL;
491 /* Append this line to any unfinished line from last time. */
493 int lastlen=strlen(add_cmd_line);
494 char *tmp=xmalloc(lastlen+strlen(cmdstr)+2);
496 memcpy(tmp,add_cmd_line,lastlen);
498 strcpy(tmp+lastlen+1,cmdstr);
500 cmdstr=add_cmd_line=tmp;
501 } else add_cmd_line=NULL;
503 /* If this line ends with backslash, request next line. */
505 if(temp && cmdstr[temp-1]=='\\') {
506 if(!add_cmd_line) add_cmd_line=strdup(cmdstr);
507 add_cmd_line[temp-1]=0;
511 /* Loop parsing all commands in this line. */
513 /* Skip leading whitespace and semicolons */
514 cmdstr += strspn(cmdstr, semicolon_whitespace);
516 /* If no more commands, exit. */
519 /* if this is a comment, jump past it and keep going */
520 if (*cmdstr == '#') {
521 /* "#n" is the same as using -n on the command line */
522 if (cmdstr[1] == 'n') be_quiet++;
523 if(!(cmdstr=strpbrk(cmdstr, "\n\r"))) break;
528 * format is: [addr][,addr][!]cmd
533 sed_cmd = xcalloc(1, sizeof(sed_cmd_t));
535 /* first part (if present) is an address: either a '$', a number or a /regex/ */
536 cmdstr += get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
538 /* second part (if present) will begin with a comma */
539 if (*cmdstr == ',') {
543 idx = get_address(cmdstr, &sed_cmd->end_line, &sed_cmd->end_match);
544 if (!idx) bb_error_msg_and_die("get_address: no address found in string\n");
548 /* skip whitespace before the command */
549 while (isspace(*cmdstr)) cmdstr++;
551 /* Check for inversion flag */
552 if (*cmdstr == '!') {
556 /* skip whitespace before the command */
557 while (isspace(*cmdstr)) cmdstr++;
560 /* last part (mandatory) will be a command */
561 if (!*cmdstr) bb_error_msg_and_die("missing command");
562 sed_cmd->cmd = *(cmdstr++);
563 cmdstr = parse_cmd_args(sed_cmd, cmdstr);
565 /* Add the command to the command array */
566 sed_cmd_tail->next = sed_cmd;
567 sed_cmd_tail = sed_cmd_tail->next;
570 /* If we glued multiple lines together, free the memory. */
577 /* Append to a string, reallocating memory as necessary. */
579 static struct pipeline {
580 char *buf; /* Space to hold string */
581 int idx; /* Space used */
582 int len; /* Space allocated */
587 static void pipe_putc(char c)
589 if(pipeline.idx==pipeline.len) {
590 pipeline.buf = xrealloc(pipeline.buf, pipeline.len + PIPE_GROW);
591 pipeline.len+=PIPE_GROW;
593 pipeline.buf[pipeline.idx++] = (c);
596 static void do_subst_w_backrefs(const char *line, const char *replace)
600 /* go through the replacement string */
601 for (i = 0; replace[i]; i++) {
602 /* if we find a backreference (\1, \2, etc.) print the backref'ed * text */
603 if (replace[i] == '\\' && replace[i+1]>'0' && replace[i+1]<='9') {
604 int backref=replace[++i]-'0';
606 /* print out the text held in regmatch[backref] */
607 if(regmatch[backref].rm_so != -1)
608 for (j = regmatch[backref].rm_so; j < regmatch[backref].rm_eo; j++)
612 /* if we find a backslash escaped character, print the character */
613 else if (replace[i] == '\\') pipe_putc(replace[++i]);
615 /* if we find an unescaped '&' print out the whole matched text. */
616 else if (replace[i] == '&')
617 for (j = regmatch[0].rm_so; j < regmatch[0].rm_eo; j++)
619 /* Otherwise just output the character. */
620 else pipe_putc(replace[i]);
624 static int do_subst_command(sed_cmd_t * sed_cmd, char **line)
626 char *oldline = *line;
629 regex_t *current_regex;
631 /* Handle empty regex. */
632 if (sed_cmd->sub_match == NULL) {
633 current_regex = previous_regex_ptr;
635 bb_error_msg_and_die("No previous regexp.");
636 } else previous_regex_ptr = current_regex = sed_cmd->sub_match;
638 /* Find the first match */
639 if(REG_NOMATCH==regexec(current_regex, oldline, 10, regmatch, 0))
642 /* Initialize temporary output buffer. */
643 pipeline.buf=xmalloc(PIPE_GROW);
644 pipeline.len=PIPE_GROW;
647 /* Now loop through, substituting for matches */
651 /* Work around bug in glibc regexec, demonstrated by:
652 echo " a.b" | busybox sed 's [^ .]* x g'
653 The match_count check is so not to break
654 echo "hi" | busybox sed 's/^/!/g' */
655 if(!regmatch[0].rm_so && !regmatch[0].rm_eo && match_count) {
656 pipe_putc(*(oldline++));
662 /* If we aren't interested in this match, output old line to
663 end of match and continue */
664 if(sed_cmd->which_match && sed_cmd->which_match!=match_count) {
665 for(i=0;i<regmatch[0].rm_eo;i++)
666 pipe_putc(oldline[i]);
670 /* print everything before the match */
671 for (i = 0; i < regmatch[0].rm_so; i++) pipe_putc(oldline[i]);
673 /* then print the substitution string */
674 do_subst_w_backrefs(oldline, sed_cmd->string);
676 /* advance past the match */
677 oldline += regmatch[0].rm_eo;
678 /* flag that something has changed */
681 /* if we're not doing this globally, get out now */
682 if (sed_cmd->which_match) break;
683 } while (*oldline && (regexec(current_regex, oldline, 10, regmatch, 0) != REG_NOMATCH));
685 /* Copy rest of string into output pipeline */
687 while(*oldline) pipe_putc(*(oldline++));
691 *line = pipeline.buf;
695 /* Set command pointer to point to this label. (Does not handle null label.) */
696 static sed_cmd_t *branch_to(const char *label)
700 for (sed_cmd = sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
701 if ((sed_cmd->cmd == ':') && (sed_cmd->string) && (strcmp(sed_cmd->string, label) == 0)) {
705 bb_error_msg_and_die("Can't find label for jump to `%s'", label);
708 /* Append copy of string to append buffer */
709 static void append(char *s)
711 struct append_list *temp=calloc(1,sizeof(struct append_list));
714 append_tail=(append_tail->next=temp);
715 else append_head=append_tail=temp;
716 temp->string=strdup(s);
719 static void flush_append(void)
721 /* Output appended lines. */
723 fprintf(nonstdout,"%s\n",append_head->string);
724 append_tail=append_head->next;
725 free(append_head->string);
727 append_head=append_tail;
729 append_head=append_tail=NULL;
732 static void add_input_file(FILE *file)
734 input_file_list=xrealloc(input_file_list,(input_file_count+1)*sizeof(FILE *));
735 input_file_list[input_file_count++]=file;
738 /* Get next line of input from input_file_list, flushing append buffer and
739 * noting if we ran out of files without a newline on the last line we read.
741 static char *get_next_line(int *no_newline)
747 while(current_input_file<input_file_count) {
748 temp=bb_get_line_from_file(input_file_list[current_input_file]);
751 *no_newline=!(len && temp[len-1]=='\n');
752 if(!*no_newline) temp[len-1]=0;
754 } else fclose(input_file_list[current_input_file++]);
760 /* Output line of text. missing_newline means the last line output did not
761 end with a newline. no_newline means this line does not end with a
764 static int puts_maybe_newline(char *s, FILE *file, int missing_newline, int no_newline)
766 if(missing_newline) fputc('\n',file);
768 if(!no_newline) fputc('\n',file);
771 fprintf(stderr,"Write failed.\n");
772 exit(4); /* It's what gnu sed exits with... */
778 #define sed_puts(s,n) missing_newline=puts_maybe_newline(s,nonstdout,missing_newline,n)
780 static void process_files(void)
782 char *pattern_space, *next_line;
783 int linenum = 0, missing_newline=0;
784 int no_newline,next_no_newline=0;
786 next_line = get_next_line(&next_no_newline);
788 /* go through every line in each file */
793 /* Advance to next line. Stop if out of lines. */
794 if(!(pattern_space=next_line)) break;
795 no_newline=next_no_newline;
797 /* Read one line in advance so we can act on the last line, the '$' address */
798 next_line = get_next_line(&next_no_newline);
801 /* for every line, go through all the commands */
802 for (sed_cmd = sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
803 int old_matched, matched;
805 old_matched = sed_cmd->in_match;
807 /* Determine if this command matches this line: */
809 /* Are we continuing a previous multi-line match? */
811 sed_cmd->in_match = sed_cmd->in_match
813 /* Or is no range necessary? */
814 || (!sed_cmd->beg_line && !sed_cmd->end_line
815 && !sed_cmd->beg_match && !sed_cmd->end_match)
817 /* Or did we match the start of a numerical range? */
818 || (sed_cmd->beg_line > 0 && (sed_cmd->beg_line == linenum))
820 /* Or does this line match our begin address regex? */
821 || (sed_cmd->beg_match &&
822 !regexec(sed_cmd->beg_match, pattern_space, 0, NULL, 0))
824 /* Or did we match last line of input? */
825 || (sed_cmd->beg_line == -1 && next_line == NULL);
827 /* Snapshot the value */
829 matched = sed_cmd->in_match;
831 /* Is this line the end of the current match? */
834 sed_cmd->in_match = !(
835 /* has the ending line come, or is this a single address command? */
837 sed_cmd->end_line==-1 ?
839 : sed_cmd->end_line<=linenum
840 : !sed_cmd->end_match)
841 /* or does this line matches our last address regex */
842 || (sed_cmd->end_match && old_matched && (regexec(sed_cmd->end_match, pattern_space, 0, NULL, 0) == 0))
846 /* Skip blocks of commands we didn't match. */
847 if (sed_cmd->cmd == '{') {
848 if(sed_cmd->invert ? matched : !matched)
849 while(sed_cmd && sed_cmd->cmd!='}') sed_cmd=sed_cmd->next;
850 if(!sed_cmd) bb_error_msg_and_die("Unterminated {");
854 /* Okay, so did this line match? */
855 if (sed_cmd->invert ? !matched : matched) {
856 /* Update last used regex in case a blank substitute BRE is found */
857 if (sed_cmd->beg_match) {
858 previous_regex_ptr = sed_cmd->beg_match;
862 switch (sed_cmd->cmd) {
864 /* Print line number */
866 fprintf(nonstdout,"%d\n", linenum);
869 /* Write the current pattern space up to the first newline */
872 char *tmp = strchr(pattern_space, '\n');
876 sed_puts(pattern_space,1);
883 /* Write the current pattern space to output */
885 sed_puts(pattern_space,no_newline);
887 /* Delete up through first newline */
890 char *tmp = strchr(pattern_space,'\n');
893 tmp=bb_xstrdup(tmp+1);
899 /* discard this line. */
903 /* Substitute with regex */
905 if(do_subst_command(sed_cmd, &pattern_space)) {
908 /* handle p option */
910 sed_puts(pattern_space,no_newline);
911 /* handle w option */
913 sed_cmd->no_newline=puts_maybe_newline(pattern_space, sed_cmd->file, sed_cmd->no_newline, no_newline);
918 /* Append line to linked list to be printed later */
921 append(sed_cmd->string);
925 /* Insert text before this line */
927 sed_puts(sed_cmd->string,1);
930 /* Cut and paste text (replace) */
932 /* Only triggers on last line of a matching range. */
933 if (!sed_cmd->in_match) sed_puts(sed_cmd->string,0);
936 /* Read file, append contents to output */
941 outfile = fopen(sed_cmd->string, "r");
945 while ((line = bb_get_chomped_line_from_file(outfile))
948 bb_xprint_and_close_file(outfile);
954 /* Write pattern space to file. */
956 sed_cmd->no_newline=puts_maybe_newline(pattern_space,sed_cmd->file, sed_cmd->no_newline,no_newline);
959 /* Read next line from input */
962 sed_puts(pattern_space,no_newline);
965 pattern_space = next_line;
966 no_newline=next_no_newline;
967 next_line = get_next_line(&next_no_newline);
973 /* Quit. End of script, end of input. */
975 /* Exit the outer while loop */
978 goto discard_commands;
980 /* Append the next line to the current line */
983 /* If no next line, jump to end of script and exit. */
984 if (next_line == NULL) {
985 /* Jump to end of script and exit */
989 /* append next_line, read new next_line. */
991 int len=strlen(pattern_space);
993 pattern_space = realloc(pattern_space, len + strlen(next_line) + 2);
994 pattern_space[len]='\n';
995 strcpy(pattern_space+len+1, next_line);
996 no_newline=next_no_newline;
997 next_line = get_next_line(&next_no_newline);
1003 /* Test/branch if substitution occurred */
1005 if(!substituted) break;
1008 /* Test/branch if substitution didn't occur */
1010 if (substituted) break;
1012 /* Branch to label */
1014 if (!sed_cmd->string) goto discard_commands;
1015 else sed_cmd = branch_to(sed_cmd->string);
1017 /* Transliterate characters */
1022 for (i = 0; pattern_space[i]; i++) {
1025 for (j = 0; sed_cmd->string[j]; j += 2) {
1026 if (pattern_space[i] == sed_cmd->string[j]) {
1027 pattern_space[i] = sed_cmd->string[j + 1];
1034 case 'g': /* Replace pattern space with hold space */
1035 free(pattern_space);
1036 pattern_space = strdup(hold_space ? hold_space : "");
1038 case 'G': /* Append newline and hold space to pattern space */
1040 int pattern_space_size = 2;
1041 int hold_space_size = 0;
1044 pattern_space_size += strlen(pattern_space);
1045 if (hold_space) hold_space_size = strlen(hold_space);
1046 pattern_space = xrealloc(pattern_space, pattern_space_size + hold_space_size);
1047 if (pattern_space_size == 2) pattern_space[0]=0;
1048 strcat(pattern_space, "\n");
1049 if (hold_space) strcat(pattern_space, hold_space);
1054 case 'h': /* Replace hold space with pattern space */
1056 hold_space = strdup(pattern_space);
1058 case 'H': /* Append newline and pattern space to hold space */
1060 int hold_space_size = 2;
1061 int pattern_space_size = 0;
1063 if (hold_space) hold_space_size += strlen(hold_space);
1065 pattern_space_size = strlen(pattern_space);
1066 hold_space = xrealloc(hold_space,
1067 hold_space_size + pattern_space_size);
1069 if (hold_space_size == 2) hold_space[0]=0;
1070 strcat(hold_space, "\n");
1071 if (pattern_space) strcat(hold_space, pattern_space);
1075 case 'x': /* Exchange hold and pattern space */
1077 char *tmp = pattern_space;
1078 pattern_space = hold_space;
1088 * exit point from sedding...
1091 /* we will print the line unless we were told to be quiet ('-n')
1092 or if the line was suppressed (ala 'd'elete) */
1093 if (!be_quiet) sed_puts(pattern_space,no_newline);
1095 /* Delete and such jump here. */
1098 free(pattern_space);
1102 /* It is possible to have a command line argument with embedded
1103 newlines. This counts as multiple command lines. */
1105 static void add_cmd_block(char *cmdstr)
1108 char *temp=bb_xstrdup(cmdstr),*temp2=temp;
1111 int len=strcspn(temp2,"\n");
1112 if(!temp2[len]) go=0;
1120 extern int sed_main(int argc, char **argv)
1122 int status = EXIT_SUCCESS, opt, getpat = 1;
1124 #ifdef CONFIG_FEATURE_CLEAN_UP
1125 /* destroy command strings on exit */
1126 if (atexit(free_and_close_stuff) == -1)
1127 bb_perror_msg_and_die("atexit");
1130 #define LIE_TO_AUTOCONF
1131 #ifdef LIE_TO_AUTOCONF
1132 if(argc==2 && !strcmp(argv[1],"--version")) {
1133 printf("This is not GNU sed version 4.0\n");
1138 /* do normal option parsing */
1139 while ((opt = getopt(argc, argv, "irne:f:")) > 0) {
1143 atexit(cleanup_outname);
1146 regex_type|=REG_EXTENDED;
1152 add_cmd_block(optarg);
1160 cmdfile = bb_xfopen(optarg, "r");
1162 while ((line = bb_get_chomped_line_from_file(cmdfile))
1168 bb_xprint_and_close_file(cmdfile);
1177 /* if we didn't get a pattern from -e or -f, use argv[optind] */
1179 if (argv[optind] == NULL)
1182 add_cmd_block(argv[optind++]);
1184 /* Flush any unfinished commands. */
1187 /* By default, we write to stdout */
1190 /* argv[(optind)..(argc-1)] should be names of file to process. If no
1191 * files were specified or '-' was specified, take input from stdin.
1192 * Otherwise, we process all the files specified. */
1193 if (argv[optind] == NULL) {
1194 if(in_place) bb_error_msg_and_die("Filename required for -i");
1195 add_input_file(stdin);
1201 for (i = optind; i < argc; i++) {
1202 if(!strcmp(argv[i], "-") && !in_place) {
1203 add_input_file(stdin);
1206 file = bb_wfopen(argv[i], "r");
1209 struct stat statbuf;
1212 outname=bb_xstrndup(argv[i],strlen(argv[i])+6);
1213 strcat(outname,"XXXXXX");
1214 if(-1==(nonstdoutfd=mkstemp(outname)))
1215 bb_error_msg_and_die("no temp file");
1216 nonstdout=fdopen(nonstdoutfd,"w");
1217 /* Set permissions of output file */
1218 fstat(fileno(file),&statbuf);
1219 fchmod(nonstdoutfd,statbuf.st_mode);
1220 add_input_file(file);
1225 rename(outname,argv[i]);
1228 } else add_input_file(file);
1230 status = EXIT_FAILURE;
1234 if(input_file_count>current_input_file) process_files();