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, d, s/match/replace/[g]
30 (Note: Specifying an address (range) to match is *optional*; commands
31 default to the whole pattern space if no specific address match was
36 - transliteration (y/source-chars/dest-chars/) (use 'tr')
37 - no support for characters other than the '/' character for regex matches
38 - no pattern space hold space storing / swapping (x, etc.)
39 - no labels / branching (: label, b, t, and friends)
40 - and lots, lots more.
45 #include <stdlib.h> /* for realloc() */
46 #include <unistd.h> /* for getopt() */
48 #include <string.h> /* for strdup() */
50 #include <ctype.h> /* for isspace() */
55 extern int optind; /* in unistd.h */
56 extern char *optarg; /* ditto */
59 static int be_quiet = 0;
64 int beg_line; /* 'sed 1p' 0 == no begining line, apply commands to all lines */
65 int end_line; /* 'sed 1,3p' 0 == no end line, use only beginning. -1 == $ */
66 regex_t *beg_match; /* sed -e '/match/cmd' */
67 regex_t *end_match; /* sed -e '/match/,/end_match/cmd' */
70 char cmd; /* p,d,s (add more at your leisure :-) */
72 /* substitution command specific fields */
73 regex_t *sub_match; /* sed -e 's/sub_match/replace/' */
74 char *replace; /* sed -e 's/sub_match/replace/' XXX: who will hold the \1 \2 \3s? */
75 unsigned int sub_g:1; /* sed -e 's/foo/bar/g' (global) */
79 static struct sed_cmd *sed_cmds = NULL; /* growable arrary holding a sequence of sed cmds */
80 static int ncmds = 0; /* number of sed commands */
82 /*static char *cur_file = NULL;*/ /* file currently being processed XXX: do I need this? */
84 static const char sed_usage[] =
85 "sed [-Vhnef] pattern [files...]\n"
86 #ifndef BB_FEATURE_TRIVIAL_HELP
88 "-n\tsuppress automatic printing of pattern space\n"
89 "-e script\tadd the script to the commands to be executed\n"
90 "-f scriptfile\tadd the contents of script-file to the commands to be executed\n"
91 "-h\tdisplay this help message\n"
92 "-V\toutput version information and exit\n"
94 "If no -e or -f is given, the first non-option argument is taken as the\n"
95 "sed script to interpret. All remaining arguments are names of input\n"
96 "files; if no input files are specified, then the standard input is read.\n"
101 static void destroy_cmd_strs()
103 if (sed_cmds == NULL)
106 /* destroy all the elements in the array */
107 while (--ncmds >= 0) {
109 if (sed_cmds[ncmds].beg_match) {
110 regfree(sed_cmds[ncmds].beg_match);
111 free(sed_cmds[ncmds].beg_match);
113 if (sed_cmds[ncmds].end_match) {
114 regfree(sed_cmds[ncmds].end_match);
115 free(sed_cmds[ncmds].end_match);
117 if (sed_cmds[ncmds].sub_match) {
118 regfree(sed_cmds[ncmds].sub_match);
119 free(sed_cmds[ncmds].sub_match);
121 if (sed_cmds[ncmds].replace)
122 free(sed_cmds[ncmds].replace);
125 /* destroy the array */
132 * trim_str - trims leading and trailing space from a string
134 * Note: This returns a malloc'ed string so you must store and free it
135 * XXX: This should be in the utility.c file.
137 static char *trim_str(const char *str)
140 char *retstr = strdup(str);
142 /* trim leading whitespace */
143 memmove(retstr, &retstr[strspn(retstr, " \n\t\v")], strlen(retstr));
145 /* trim trailing whitespace */
146 i = strlen(retstr) - 1;
147 while (isspace(retstr[i]))
153 * you know, a strrspn() would really be nice cuz then we could say:
155 * retstr[strlen(retstr) - strrspn(retstr, " \n\t\v") + 1] = 0;
162 * index_of_unescaped_slash - walks left to right through a string beginning
163 * at a specified index and returns the index of the next unescaped slash.
165 static int index_of_next_unescaped_slash(const char *str, int idx)
169 /* test if we've hit the end */
172 } while (str[idx] != '/' && str[idx - 1] != '\\');
178 * returns the index in the string just past where the address ends.
180 static int get_address(const char *str, int *line, regex_t **regex)
182 char *my_str = strdup(str);
185 if (isdigit(my_str[idx])) {
188 } while (isdigit(my_str[idx]));
190 *line = atoi(my_str);
193 else if (my_str[idx] == '$') {
198 else if (my_str[idx] == '/') {
199 idx = index_of_next_unescaped_slash(my_str, idx);
201 fatalError("unterminated match expression\n");
203 *regex = (regex_t *)xmalloc(sizeof(regex_t));
204 xregcomp(*regex, my_str+1, REG_NEWLINE);
207 fprintf(stderr, "sed.c:get_address: no address found in string\n");
208 fprintf(stderr, "\t(you probably didn't check the string you passed me)\n");
216 static char *strdup_substr(const char *str, int start, int end)
218 int size = end - start + 1;
219 char *newstr = xmalloc(size);
220 memcpy(newstr, str+start, size-1);
221 newstr[size-1] = '\0';
225 static void parse_subst_cmd(struct sed_cmd *sed_cmd, const char *substr)
227 int oldidx, cflags = REG_NEWLINE;
232 * the string that gets passed to this function should look like this:
237 * (all three of the '/' slashes are mandatory)
240 /* verify that the 's' is followed by a 'slash' */
241 if (substr[++idx] != '/')
242 fatalError("bad format in substitution expression\n");
244 /* save the match string */
246 idx = index_of_next_unescaped_slash(substr, idx);
248 fatalError("bad format in substitution expression\n");
249 match = strdup_substr(substr, oldidx, idx);
251 /* save the replacement string */
253 idx = index_of_next_unescaped_slash(substr, idx);
255 fatalError("bad format in substitution expression\n");
256 sed_cmd->replace = strdup_substr(substr, oldidx, idx);
258 /* process the flags */
259 while (substr[++idx]) {
260 switch (substr[idx]) {
268 fatalError("bad option in substitution expression\n");
272 /* compile the regex */
273 sed_cmd->sub_match = (regex_t *)xmalloc(sizeof(regex_t));
274 xregcomp(sed_cmd->sub_match, match, cflags);
278 static void parse_cmd_str(struct sed_cmd *sed_cmd, const char *cmdstr)
283 * format is: [addr][,addr]cmd
288 /* first part (if present) is an address: either a number or a /regex/ */
289 if (isdigit(cmdstr[idx]) || cmdstr[idx] == '/')
290 idx = get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
292 /* second part (if present) will begin with a comma */
293 if (cmdstr[idx] == ',')
294 idx += get_address(&cmdstr[++idx], &sed_cmd->end_line, &sed_cmd->end_match);
296 /* last part (mandatory) will be a command */
297 if (cmdstr[idx] == '\0')
298 fatalError("missing command\n");
299 if (!strchr("pds", cmdstr[idx])) /* <-- XXX add new commands here */
300 fatalError("invalid command\n");
301 sed_cmd->cmd = cmdstr[idx];
303 /* special-case handling for (s)ubstitution */
304 if (sed_cmd->cmd == 's')
305 parse_subst_cmd(sed_cmd, &cmdstr[idx]);
308 static void add_cmd_str(const char *cmdstr)
310 char *my_cmdstr = trim_str(cmdstr);
312 /* if this is a comment, don't even bother */
313 if (my_cmdstr[0] == '#') {
319 sed_cmds = realloc(sed_cmds, sizeof(struct sed_cmd) * (++ncmds));
320 /* zero new element */
321 memset(&sed_cmds[ncmds-1], 0, sizeof(struct sed_cmd));
322 /* load command string into new array element */
323 parse_cmd_str(&sed_cmds[ncmds-1], my_cmdstr);
327 static void load_cmd_file(char *filename)
332 cmdfile = fopen(filename, "r");
334 fatalError(strerror(errno));
336 while ((line = get_line_from_file(cmdfile)) != NULL) {
337 line[strlen(line)-1] = 0; /* eat newline */
343 static int do_subst_command(const struct sed_cmd *sed_cmd, const char *line)
347 /* we only substitute if the substitution 'search' expression matches */
348 if (regexec(sed_cmd->sub_match, line, 0, NULL, 0) == 0) {
351 char *ptr = (char *)line;
354 /* if we can match the search string... */
355 if (regexec(sed_cmd->sub_match, ptr, 1, ®match, 0) == 0) {
356 /* print everything before the match, */
357 for (i = 0; i < regmatch.rm_so; i++)
358 fputc(ptr[i], stdout);
359 /* then print the substitution in its place */
360 fputs(sed_cmd->replace, stdout);
361 /* then advance past the match */
362 ptr += regmatch.rm_eo;
363 /* and let the calling function know that something
364 * has been changed */
367 /* if we're not doing this globally... */
371 /* if we COULD NOT match the search string (meaning we've gone past
372 * all previous instances), get out */
377 /* is there anything left to print? */
385 static int do_sed_command(const struct sed_cmd *sed_cmd, const char *line)
389 switch (sed_cmd->cmd) {
400 altered = do_subst_command(sed_cmd, line);
407 static void process_file(FILE *file)
410 static int linenum = 0; /* GNU sed does not restart counting lines at EOF */
411 unsigned int still_in_range = 0;
415 /* go through every line in the file */
416 while ((line = get_line_from_file(file)) != NULL) {
421 /* for every line, go through all the commands */
422 for (i = 0; i < ncmds; i++) {
424 /* are we acting on a range of matched lines? */
425 if (sed_cmds[i].beg_match && sed_cmds[i].end_match) {
426 if (still_in_range || regexec(sed_cmds[i].beg_match, line, 0, NULL, 0) == 0) {
427 line_altered += do_sed_command(&sed_cmds[i], line);
429 if (regexec(sed_cmds[i].end_match, line, 0, NULL, 0) == 0)
434 /* are we trying to match a single line? */
435 else if (sed_cmds[i].beg_match) {
436 if (regexec(sed_cmds[i].beg_match, line, 0, NULL, 0) == 0)
437 line_altered += do_sed_command(&sed_cmds[i], line);
440 /* are we acting on a range of line numbers? */
441 else if (sed_cmds[i].beg_line > 0 && sed_cmds[i].end_line > 0) {
442 if (linenum >= sed_cmds[i].beg_line && linenum <= sed_cmds[i].end_line)
443 line_altered += do_sed_command(&sed_cmds[i], line);
446 /* are we acting on a specified line number */
447 else if (sed_cmds[i].beg_line > 0) {
448 if (linenum == sed_cmds[i].beg_line)
449 line_altered += do_sed_command(&sed_cmds[i], line);
452 /* not acting on matches or line numbers. act on every line */
454 line_altered += do_sed_command(&sed_cmds[i], line);
458 /* we will print the line unless we were told to be quiet or if the
459 * line was altered (via a 'd'elete or 's'ubstitution) */
460 if (!be_quiet && !line_altered)
467 extern int sed_main(int argc, char **argv)
471 /* do special-case option parsing */
472 if (argv[1] && (strcmp(argv[1], "--help") == 0))
476 /* destroy command strings on exit */
477 if (atexit(destroy_cmd_strs) == -1) {
483 /* do normal option parsing */
484 while ((opt = getopt(argc, argv, "Vhne:f:")) > 0) {
487 printf("Print Busybox version here\n");
500 load_cmd_file(optarg);
505 /* if we didn't get a pattern from a -e and no command file was specified,
506 * argv[optind] should be the pattern. no pattern, no worky */
508 if (argv[optind] == NULL)
511 add_cmd_str(argv[optind]);
517 /* argv[(optind)..(argc-1)] should be names of file to process. If no
518 * files were specified or '-' was specified, take input from stdin.
519 * Otherwise, we process all the files specified. */
520 if (argv[optind] == NULL || (strcmp(argv[optind], "-") == 0)) {
526 for (i = optind; i < argc; i++) {
527 file = fopen(argv[i], "r");
529 fprintf(stderr, "sed: %s: %s\n", argv[i], strerror(errno));