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(int idx, const char *str)
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(idx, my_str);
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_cmd_str(struct sed_cmd *sed_cmd, const char *cmdstr)
230 * format is: [addr][,addr]cmd
235 /* first part (if present) is an address: either a number or a /regex/ */
236 if (isdigit(cmdstr[idx]) || cmdstr[idx] == '/')
237 idx = get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
239 /* second part (if present) will begin with a comma */
240 if (cmdstr[idx] == ',')
241 idx += get_address(&cmdstr[++idx], &sed_cmd->end_line, &sed_cmd->end_match);
243 /* last part (mandatory) will be a command */
244 if (cmdstr[idx] == '\0')
245 fatalError("missing command\n");
246 if (!strchr("pds", cmdstr[idx])) /* <-- XXX add new commands here */
247 fatalError("invalid command\n");
248 sed_cmd->cmd = cmdstr[idx];
249 /* special-case handling for 's' */
250 if (sed_cmd->cmd == 's') {
251 int oldidx, cflags = REG_NEWLINE;
253 /* format for substitution is:
259 /* verify that we have an 's' followed by a 'slash' */
260 if (cmdstr[++idx] != '/')
261 fatalError("bad format in substitution expression\n");
263 /* save the match string */
265 idx = index_of_next_unescaped_slash(idx, cmdstr);
267 fatalError("bad format in substitution expression\n");
268 match = strdup_substr(cmdstr, oldidx, idx);
270 /* save the replacement string */
272 idx = index_of_next_unescaped_slash(idx, cmdstr);
274 fatalError("bad format in substitution expression\n");
275 sed_cmd->replace = strdup_substr(cmdstr, oldidx, idx);
277 /* process the flags */
278 while (cmdstr[++idx]) {
279 switch (cmdstr[idx]) {
287 fatalError("bad option in substitution expression\n");
291 /* compile the regex */
292 sed_cmd->sub_match = (regex_t *)xmalloc(sizeof(regex_t));
293 xregcomp(sed_cmd->sub_match, match, cflags);
298 static void add_cmd_str(const char *cmdstr)
300 char *my_cmdstr = trim_str(cmdstr);
302 /* if this is a comment, don't even bother */
303 if (my_cmdstr[0] == '#') {
309 sed_cmds = realloc(sed_cmds, sizeof(struct sed_cmd) * (++ncmds));
310 /* zero new element */
311 memset(&sed_cmds[ncmds-1], 0, sizeof(struct sed_cmd));
312 /* load command string into new array element */
313 parse_cmd_str(&sed_cmds[ncmds-1], my_cmdstr);
317 static void load_cmd_file(char *filename)
322 cmdfile = fopen(filename, "r");
324 fatalError(strerror(errno));
326 while ((line = get_line_from_file(cmdfile)) != NULL) {
327 line[strlen(line)-1] = 0; /* eat newline */
334 static int do_sed_command(const struct sed_cmd *sed_cmd, const char *line)
338 switch (sed_cmd->cmd) {
348 case 's': /* oo, a fun one :-) */
350 /* we only substitute if the substitution 'search' expression matches */
351 if (regexec(sed_cmd->sub_match, line, 0, NULL, 0) == 0) {
354 char *ptr = (char *)line;
357 /* if we can match the search string... */
358 if (regexec(sed_cmd->sub_match, ptr, 1, ®match, 0) == 0) {
359 /* print everything before the match, */
360 for (i = 0; i < regmatch.rm_so; i++)
361 fputc(ptr[i], stdout);
362 /* then print the substitution in its place */
363 fputs(sed_cmd->replace, stdout);
364 /* then advance past the match */
365 ptr += regmatch.rm_eo;
366 /* and let the calling function know that something
367 * has been changed */
370 /* if we're not doing this globally... */
374 /* if we COULD NOT match the search string (meaning we've gone past
375 * all previous instances), get out */
380 /* is there anything left to print? */
391 static void process_file(FILE *file)
394 static int linenum = 0; /* GNU sed does not restart counting lines at EOF */
395 unsigned int still_in_range = 0;
399 /* go through every line in the file */
400 while ((line = get_line_from_file(file)) != NULL) {
405 /* for every line, go through all the commands */
406 for (i = 0; i < ncmds; i++) {
408 /* are we acting on a range of matched lines? */
409 if (sed_cmds[i].beg_match && sed_cmds[i].end_match) {
410 if (still_in_range || regexec(sed_cmds[i].beg_match, line, 0, NULL, 0) == 0) {
411 line_altered += do_sed_command(&sed_cmds[i], line);
413 if (regexec(sed_cmds[i].end_match, line, 0, NULL, 0) == 0)
418 /* are we trying to match a single line? */
419 else if (sed_cmds[i].beg_match) {
420 if (regexec(sed_cmds[i].beg_match, line, 0, NULL, 0) == 0)
421 line_altered += do_sed_command(&sed_cmds[i], line);
424 /* are we acting on a range of line numbers? */
425 else if (sed_cmds[i].beg_line > 0 && sed_cmds[i].end_line > 0) {
426 if (linenum >= sed_cmds[i].beg_line && linenum <= sed_cmds[i].end_line)
427 line_altered += do_sed_command(&sed_cmds[i], line);
430 /* are we acting on a specified line number */
431 else if (sed_cmds[i].beg_line > 0) {
432 if (linenum == sed_cmds[i].beg_line)
433 line_altered += do_sed_command(&sed_cmds[i], line);
436 /* not acting on matches or line numbers. act on every line */
438 line_altered += do_sed_command(&sed_cmds[i], line);
442 /* we will print the line unless we were told to be quiet or if the
443 * line was altered (via a 'd'elete or 's'ubstitution) */
444 if (!be_quiet && !line_altered)
451 extern int sed_main(int argc, char **argv)
455 /* do special-case option parsing */
456 if (argv[1] && (strcmp(argv[1], "--help") == 0))
460 /* destroy command strings on exit */
461 if (atexit(destroy_cmd_strs) == -1) {
467 /* do normal option parsing */
468 while ((opt = getopt(argc, argv, "Vhne:f:")) > 0) {
471 printf("Print Busybox version here\n");
484 load_cmd_file(optarg);
489 /* if we didn't get a pattern from a -e and no command file was specified,
490 * argv[optind] should be the pattern. no pattern, no worky */
492 if (argv[optind] == NULL)
495 add_cmd_str(argv[optind]);
501 /* argv[(optind)..(argc-1)] should be names of file to process. If no
502 * files were specified or '-' was specified, take input from stdin.
503 * Otherwise, we process all the files specified. */
504 if (argv[optind] == NULL || (strcmp(argv[optind], "-") == 0)) {
510 for (i = optind; i < argc; i++) {
511 file = fopen(argv[i], "r");
513 fprintf(stderr, "sed: %s: %s\n", argv[i], strerror(errno));