2 * sed.c - very minimalist version of sed
4 * Copyright (C) 1999,2000 by Lineo, inc.
5 * Written by Mark Whitley <markw@lineo.com>, <markw@enol.com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 Supported features and commands in this version of sed:
27 - address matching: num|/matchstr/[,num|/matchstr/|$]command
28 - commands: (p)rint, (d)elete, (s)ubstitue (with g & I flags)
29 - edit commands: (a)ppend, (i)nsert, (c)hange
30 - backreferences in substitution expressions (\1, \2...\9)
32 (Note: Specifying an address (range) to match is *optional*; commands
33 default to the whole pattern space if no specific address match was
38 - transliteration (y/source-chars/dest-chars/) (use 'tr')
39 - no support for characters other than the '/' character for regex matches
40 - no pattern space hold space storing / swapping (x, etc.)
41 - no labels / branching (: label, b, t, and friends)
42 - and lots, lots more.
47 #include <unistd.h> /* for getopt() */
49 #include <string.h> /* for strdup() */
51 #include <ctype.h> /* for isspace() */
54 #define bb_need_full_version
55 #define BB_DECLARE_EXTERN
59 extern int optind; /* in unistd.h */
60 extern char *optarg; /* ditto */
63 static int be_quiet = 0;
65 static const int SUB_G = 1 << 0;
66 #ifdef BB_FEATURE_SED_PATTERN_SPACE
67 static const int SUB_P = 1 << 1;
73 int beg_line; /* 'sed 1p' 0 == no begining line, apply commands to all lines */
74 int end_line; /* 'sed 1,3p' 0 == no end line, use only beginning. -1 == $ */
75 regex_t *beg_match; /* sed -e '/match/cmd' */
76 regex_t *end_match; /* sed -e '/match/,/end_match/cmd' */
79 char cmd; /* p,d,s (add more at your leisure :-) */
81 /* substitution command specific fields */
82 regex_t *sub_match; /* sed -e 's/sub_match/replace/' */
83 char *replace; /* sed -e 's/sub_match/replace/' XXX: who will hold the \1 \2 \3s? */
84 unsigned int num_backrefs:4; /* how many back references (\1..\9) */
85 /* Note: GNU/POSIX sed does not save more than nine backrefs, so
86 * we only use 4 bits to hold the number */
87 #ifndef BB_FEATURE_SED_PATTERN_SPACE
88 unsigned int sub_flags:1; /* sed -e 's/foo/bar/g' (global) */
90 unsigned int sub_flags:2; /* sed -e 's/foo/bar/gp' (global/pattern) */
93 /* edit command (a,i,c) speicific field */
98 static struct sed_cmd *sed_cmds = NULL; /* growable arrary holding a sequence of sed cmds */
99 static int ncmds = 0; /* number of sed commands */
101 /*static char *cur_file = NULL;*/ /* file currently being processed XXX: do I need this? */
103 #ifdef BB_FEATURE_CLEAN_UP
104 static void destroy_cmd_strs()
106 if (sed_cmds == NULL)
109 /* destroy all the elements in the array */
110 while (--ncmds >= 0) {
112 if (sed_cmds[ncmds].beg_match) {
113 regfree(sed_cmds[ncmds].beg_match);
114 free(sed_cmds[ncmds].beg_match);
116 if (sed_cmds[ncmds].end_match) {
117 regfree(sed_cmds[ncmds].end_match);
118 free(sed_cmds[ncmds].end_match);
120 if (sed_cmds[ncmds].sub_match) {
121 regfree(sed_cmds[ncmds].sub_match);
122 free(sed_cmds[ncmds].sub_match);
124 if (sed_cmds[ncmds].replace)
125 free(sed_cmds[ncmds].replace);
128 /* destroy the array */
136 * trim_str - trims leading and trailing space from a string
138 * Note: This returns a malloc'ed string so you must store and free it
139 * XXX: This should be in the utility.c file.
140 * XXX: This is now obsolete. Maybe it belongs nowhere.
142 static char *trim_str(const char *str)
145 char *retstr = strdup(str);
147 /* trim leading whitespace */
148 memmove(retstr, &retstr[strspn(retstr, " \n\t\v")], strlen(retstr));
150 /* trim trailing whitespace */
151 i = strlen(retstr) - 1;
152 while (isspace(retstr[i]))
158 * you know, a strrspn() would really be nice cuz then we could say:
160 * retstr[strrspn(retstr, " \n\t\v") + 1] = 0;
169 * strrspn - works just like strspn() but goes from right to left instead of
172 static size_t strrspn(const char *s, const char *accept)
174 size_t i = strlen(s);
176 while (strchr(accept, s[--i]))
184 * index_of_next_unescaped_slash - walks left to right through a string
185 * beginning at a specified index and returns the index of the next forward
186 * slash ('/') not preceeded by a backslash ('\').
188 static int index_of_next_unescaped_slash(const char *str, int idx)
190 for ( ; str[idx]; idx++) {
191 if (str[idx] == '/' && str[idx-1] != '\\')
195 /* if we make it to here, we've hit the end of the string */
200 * returns the index in the string just past where the address ends.
202 static int get_address(const char *str, int *line, regex_t **regex)
204 char *my_str = strdup(str);
207 if (isdigit(my_str[idx])) {
210 } while (isdigit(my_str[idx]));
212 *line = atoi(my_str);
214 else if (my_str[idx] == '$') {
218 else if (my_str[idx] == '/') {
219 idx = index_of_next_unescaped_slash(my_str, ++idx);
221 fatalError("unterminated match expression\n");
223 *regex = (regex_t *)xmalloc(sizeof(regex_t));
224 xregcomp(*regex, my_str+1, REG_NEWLINE);
225 idx++; /* so it points to the next character after the last '/' */
228 errorMsg("get_address: no address found in string\n"
229 "\t(you probably didn't check the string you passed me)\n");
237 static char *strdup_substr(const char *str, int start, int end)
239 int size = end - start + 1;
240 char *newstr = xmalloc(size);
241 memcpy(newstr, str+start, size-1);
242 newstr[size-1] = '\0';
246 static int parse_subst_cmd(struct sed_cmd *sed_cmd, const char *substr)
248 int oldidx, cflags = REG_NEWLINE;
254 * the string that gets passed to this function should look like this:
255 * s/match/replace/gIp
259 * (all three of the '/' slashes are mandatory)
262 /* verify that the 's' is followed by a 'slash' */
263 if (substr[++idx] != '/')
264 fatalError("bad format in substitution expression\n");
266 /* save the match string */
268 idx = index_of_next_unescaped_slash(substr, ++idx);
270 fatalError("bad format in substitution expression\n");
271 match = strdup_substr(substr, oldidx, idx);
273 /* determine the number of back references in the match string */
274 /* Note: we compute this here rather than in the do_subst_command()
275 * function to save processor time, at the expense of a little more memory
276 * (4 bits) per sed_cmd */
278 /* sed_cmd->num_backrefs = 0; */ /* XXX: not needed? --apparently not */
279 for (j = 0; match[j]; j++) {
280 /* GNU/POSIX sed does not save more than nine backrefs */
281 if (match[j] == '\\' && match[j+1] == '(' && sed_cmd->num_backrefs < 9)
282 sed_cmd->num_backrefs++;
285 /* save the replacement string */
287 idx = index_of_next_unescaped_slash(substr, ++idx);
289 fatalError("bad format in substitution expression\n");
290 sed_cmd->replace = strdup_substr(substr, oldidx, idx);
292 /* process the flags */
293 while (substr[++idx]) {
294 switch (substr[idx]) {
296 sed_cmd->sub_flags = SUB_G;
301 #ifdef BB_FEATURE_SED_PATTERN_SPACE
303 sed_cmd->sub_flags = SUB_P;
307 /* any whitespace or semicolon trailing after a s/// is ok */
308 if (strchr("; \t\v\n\r", substr[idx]))
311 fatalError("bad option in substitution expression\n");
316 /* compile the match string into a regex */
317 sed_cmd->sub_match = (regex_t *)xmalloc(sizeof(regex_t));
318 xregcomp(sed_cmd->sub_match, match, cflags);
324 static int parse_edit_cmd(struct sed_cmd *sed_cmd, const char *editstr)
327 int slashes_eaten = 0;
328 char *ptr; /* shorthand */
331 * the string that gets passed to this function should look like this:
335 * | this backslash (immediately following the edit command) is mandatory
342 * as soon as we hit a TEXT line that has no trailing '\', we're done.
343 * this means a command like:
352 if (editstr[1] != '\\' && (editstr[2] != '\n' || editstr[2] != '\r'))
353 fatalError("bad format in edit expression\n");
355 /* store the edit line text */
356 /* make editline big enough to accomodate the extra '\n' we will tack on
358 sed_cmd->editline = xmalloc(strlen(&editstr[3]) + 2);
359 strcpy(sed_cmd->editline, &editstr[3]);
360 ptr = sed_cmd->editline;
362 /* now we need to go through * and: s/\\[\r\n]$/\n/g on the edit line */
364 while (ptr[idx] != '\\' && (ptr[idx+1] != '\n' || ptr[idx+1] != '\r')) {
370 /* move the newline over the '\' before it (effectively eats the '\') */
371 memmove(&ptr[idx], &ptr[idx+1], strlen(&ptr[idx+1]));
372 ptr[strlen(ptr)-1] = 0;
374 /* substitue \r for \n if needed */
375 if (ptr[idx] == '\r')
383 /* this accounts for discrepancies between the modified string and the
384 * original string passed in to this function */
385 idx += slashes_eaten;
387 /* this accounts for the fact that A) we started at index 3, not at index
388 * 0 and B) that we added an extra '\n' at the end (if you think the next
389 * line should read 'idx += 4' remember, arrays are zero-based) */
396 static char *parse_cmd_str(struct sed_cmd *sed_cmd, const char *cmdstr)
401 * format is: [addr][,addr]cmd
407 /* first part (if present) is an address: either a number or a /regex/ */
408 if (isdigit(cmdstr[idx]) || cmdstr[idx] == '/')
409 idx = get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
411 /* second part (if present) will begin with a comma */
412 if (cmdstr[idx] == ',')
413 idx += get_address(&cmdstr[++idx], &sed_cmd->end_line, &sed_cmd->end_match);
415 /* last part (mandatory) will be a command */
416 if (cmdstr[idx] == '\0')
417 fatalError("missing command\n");
418 if (!strchr("pdsaic", cmdstr[idx])) /* <-- XXX add new commands here */
419 fatalError("invalid command\n");
420 sed_cmd->cmd = cmdstr[idx];
422 /* special-case handling for (s)ubstitution */
423 if (sed_cmd->cmd == 's') {
424 idx += parse_subst_cmd(sed_cmd, &cmdstr[idx]);
426 /* special-case handling for (a)ppend, (i)nsert, and (c)hange */
427 else if (strchr("aic", cmdstr[idx])) {
428 if (sed_cmd->end_line || sed_cmd->end_match)
429 fatalError("only a beginning address can be specified for edit commands\n");
430 idx += parse_edit_cmd(sed_cmd, &cmdstr[idx]);
432 /* if it was a single-letter command (such as 'p' or 'd') we need to
433 * increment the index past that command */
437 /* give back whatever's left over */
438 return (char *)&cmdstr[idx];
441 static void add_cmd_str(const char *cmdstr)
443 char *mystr = (char *)cmdstr;
447 /* trim leading whitespace and semicolons */
448 memmove(mystr, &mystr[strspn(mystr, "; \n\r\t\v")], strlen(mystr));
449 /* if we ate the whole thing, that means there was just trailing
450 * whitespace or a final / no-op semicolon. either way, get out */
451 if (strlen(mystr) == 0)
453 /* if this is a comment, jump past it and keep going */
454 if (mystr[0] == '#') {
455 mystr = strpbrk(mystr, ";\n\r");
459 sed_cmds = xrealloc(sed_cmds, sizeof(struct sed_cmd) * (++ncmds));
460 /* zero new element */
461 memset(&sed_cmds[ncmds-1], 0, sizeof(struct sed_cmd));
462 /* load command string into new array element, get remainder */
463 mystr = parse_cmd_str(&sed_cmds[ncmds-1], mystr);
465 } while (mystr && strlen(mystr));
469 static void load_cmd_file(char *filename)
475 cmdfile = fopen(filename, "r");
477 fatalError(strerror(errno));
479 while ((line = get_line_from_file(cmdfile)) != NULL) {
480 /* if a line ends with '\' it needs the next line appended to it */
481 while (line[strlen(line)-2] == '\\' &&
482 (nextline = get_line_from_file(cmdfile)) != NULL) {
483 line = xrealloc(line, strlen(line) + strlen(nextline) + 1);
484 strcat(line, nextline);
487 /* eat trailing newline (if any) --if I don't do this, edit commands
488 * (aic) will print an extra newline */
489 if (line[strlen(line)-1] == '\n')
490 line[strlen(line)-1] = 0;
496 static void print_subst_w_backrefs(const char *line, const char *replace, regmatch_t *regmatch)
500 /* go through the replacement string */
501 for (i = 0; replace[i]; i++) {
502 /* if we find a backreference (\1, \2, etc.) print the backref'ed * text */
503 if (replace[i] == '\\' && isdigit(replace[i+1])) {
507 ++i; /* i now indexes the backref number, instead of the leading slash */
508 tmpstr[0] = replace[i];
510 backref = atoi(tmpstr);
511 /* print out the text held in regmatch[backref] */
512 for (j = regmatch[backref].rm_so; j < regmatch[backref].rm_eo; j++)
513 fputc(line[j], stdout);
516 /* if we find a backslash escaped character, print the character */
517 else if (replace[i] == '\\') {
519 fputc(replace[i], stdout);
522 /* if we find an unescaped '&' print out the whole matched text.
523 * fortunately, regmatch[0] contains the indicies to the whole matched
524 * expression (kinda seems like it was designed for just such a
526 else if (replace[i] == '&' && replace[i-1] != '\\') {
528 for (j = regmatch[0].rm_so; j < regmatch[0].rm_eo; j++)
529 fputc(line[j], stdout);
531 /* nothing special, just print this char of the replacement string to stdout */
533 fputc(replace[i], stdout);
537 static int do_subst_command(const struct sed_cmd *sed_cmd, const char *line)
541 /* we only substitute if the substitution 'search' expression matches */
542 if (regexec(sed_cmd->sub_match, line, 0, NULL, 0) == 0) {
543 regmatch_t *regmatch = xmalloc(sizeof(regmatch_t) * (sed_cmd->num_backrefs+1));
545 char *ptr = (char *)line;
548 /* if we can match the search string... */
549 if (regexec(sed_cmd->sub_match, ptr, sed_cmd->num_backrefs+1, regmatch, 0) == 0) {
550 /* print everything before the match, */
551 for (i = 0; i < regmatch[0].rm_so; i++) {
552 #ifdef BB_FEATURE_SED_PATTERN_SPACE
553 if(!be_quiet || (sed_cmd->sub_flags & SUB_P))
555 fputc(ptr[i], stdout);
558 /* then print the substitution in its place */
559 #ifdef BB_FEATURE_SED_PATTERN_SPACE
560 if(!be_quiet || (sed_cmd->sub_flags & SUB_P))
562 print_subst_w_backrefs(ptr, sed_cmd->replace, regmatch);
564 /* then advance past the match */
565 ptr += regmatch[0].rm_eo;
567 /* and flag that something has changed */
570 /* if we're not doing this globally... */
571 if (!sed_cmd->sub_flags & SUB_G)
574 /* if we COULD NOT match the search string (meaning we've gone past
575 * all previous instances), get out */
580 /* is there anything left to print? */
581 #ifdef BB_FEATURE_SED_PATTERN_SPACE
582 if (*ptr && (!be_quiet || sed_cmds->sub_flags & SUB_P))
595 static int do_sed_command(const struct sed_cmd *sed_cmd, const char *line)
599 switch (sed_cmd->cmd) {
610 altered = do_subst_command(sed_cmd, line);
615 fputs(sed_cmd->editline, stdout);
620 fputs(sed_cmd->editline, stdout);
624 fputs(sed_cmd->editline, stdout);
632 static void process_file(FILE *file)
635 static int linenum = 0; /* GNU sed does not restart counting lines at EOF */
636 unsigned int still_in_range = 0;
640 /* go through every line in the file */
641 while ((line = get_line_from_file(file)) != NULL) {
646 /* for every line, go through all the commands */
647 for (i = 0; i < ncmds; i++) {
649 /* are we acting on a range of matched lines? */
650 if (sed_cmds[i].beg_match && sed_cmds[i].end_match) {
651 if (still_in_range || regexec(sed_cmds[i].beg_match, line, 0, NULL, 0) == 0) {
652 line_altered += do_sed_command(&sed_cmds[i], line);
654 if (regexec(sed_cmds[i].end_match, line, 0, NULL, 0) == 0)
659 /* are we trying to match a single line? */
660 else if (sed_cmds[i].beg_match) {
661 if (regexec(sed_cmds[i].beg_match, line, 0, NULL, 0) == 0)
662 line_altered += do_sed_command(&sed_cmds[i], line);
665 /* are we acting on a range of line numbers? */
666 else if (sed_cmds[i].beg_line > 0 && sed_cmds[i].end_line != 0) {
667 if (linenum >= sed_cmds[i].beg_line && (sed_cmds[i].end_line == -1 || linenum <= sed_cmds[i].end_line))
668 line_altered += do_sed_command(&sed_cmds[i], line);
671 /* are we acting on a specified line number */
672 else if (sed_cmds[i].beg_line > 0) {
673 if (linenum == sed_cmds[i].beg_line)
674 line_altered += do_sed_command(&sed_cmds[i], line);
677 /* not acting on matches or line numbers. act on every line */
679 line_altered += do_sed_command(&sed_cmds[i], line);
683 /* we will print the line unless we were told to be quiet or if
684 * the line was altered (via a 'd'elete or 's'ubstitution) */
685 #ifndef BB_FEATURE_SED_PATTERN_SPACE
686 if (!be_quiet &&!line_altered)
688 /* we where specificly requested to print the output */
689 if ((!be_quiet || (sed_cmds[i].sub_flags & SUB_P)) && !line_altered)
697 extern int sed_main(int argc, char **argv)
701 #ifdef BB_FEATURE_CLEAN_UP
702 /* destroy command strings on exit */
703 if (atexit(destroy_cmd_strs) == -1) {
709 /* do normal option parsing */
710 while ((opt = getopt(argc, argv, "hne:f:")) > 0) {
722 load_cmd_file(optarg);
727 /* if we didn't get a pattern from a -e and no command file was specified,
728 * argv[optind] should be the pattern. no pattern, no worky */
730 if (argv[optind] == NULL)
733 add_cmd_str(argv[optind]);
739 /* argv[(optind)..(argc-1)] should be names of file to process. If no
740 * files were specified or '-' was specified, take input from stdin.
741 * Otherwise, we process all the files specified. */
742 if (argv[optind] == NULL || (strcmp(argv[optind], "-") == 0)) {
748 for (i = optind; i < argc; i++) {
749 file = fopen(argv[i], "r");
751 errorMsg("%s: %s\n", argv[i], strerror(errno));