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"
100 static void destroy_cmd_strs()
102 if (sed_cmds == NULL)
105 /* destroy all the elements in the array */
106 while (--ncmds >= 0) {
108 if (sed_cmds[ncmds].beg_match) {
109 regfree(sed_cmds[ncmds].beg_match);
110 free(sed_cmds[ncmds].beg_match);
112 if (sed_cmds[ncmds].end_match) {
113 regfree(sed_cmds[ncmds].end_match);
114 free(sed_cmds[ncmds].end_match);
116 if (sed_cmds[ncmds].sub_match) {
117 regfree(sed_cmds[ncmds].sub_match);
118 free(sed_cmds[ncmds].sub_match);
120 if (sed_cmds[ncmds].replace)
121 free(sed_cmds[ncmds].replace);
124 /* destroy the array */
129 static void exit_sed(int retcode, const char *message)
133 fputs(message, stderr);
138 * trim_str - trims leading and trailing space from a string
140 * Note: This returns a malloc'ed string so you must store and free it
141 * XXX: This should be in the utility.c file.
143 static char *trim_str(const char *str)
146 char *retstr = strdup(str);
148 /* trim leading whitespace */
149 memmove(retstr, &retstr[strspn(retstr, " \n\t\v")], strlen(retstr));
151 /* trim trailing whitespace */
152 i = strlen(retstr) - 1;
153 while (isspace(retstr[i]))
159 * you know, a strrspn() would really be nice cuz then we could say:
161 * retstr[strlen(retstr) - strrspn(retstr, " \n\t\v") + 1] = 0;
168 * index_of_unescaped_slash - walks left to right through a string beginning
169 * at a specified index and returns the index of the next unescaped slash.
171 static int index_of_next_unescaped_slash(int idx, const char *str)
175 /* test if we've hit the end */
178 } while (str[idx] != '/' && str[idx - 1] != '\\');
184 * returns the index in the string just past where the address ends.
186 static int get_address(const char *str, int *line, regex_t **regex)
188 char *my_str = strdup(str);
191 if (isdigit(my_str[idx])) {
194 } while (isdigit(my_str[idx]));
196 *line = atoi(my_str);
199 else if (my_str[idx] == '$') {
204 else if (my_str[idx] == '/') {
205 idx = index_of_next_unescaped_slash(idx, my_str);
207 exit_sed(1, "sed: unterminated match expression\n");
209 *regex = (regex_t *)xmalloc(sizeof(regex_t));
210 if (bb_regcomp(*regex, my_str+1, REG_NEWLINE) != 0) {
216 fprintf(stderr, "sed.c:get_address: no address found in string\n");
217 fprintf(stderr, "\t(you probably didn't check the string you passed me)\n");
225 static char *strdup_substr(const char *str, int start, int end)
227 int size = end - start + 1;
228 char *newstr = xmalloc(size);
229 memcpy(newstr, str+start, size-1);
230 newstr[size-1] = '\0';
234 static void parse_cmd_str(struct sed_cmd *sed_cmd, const char *cmdstr)
239 * format is: [addr][,addr]cmd
244 /* first part (if present) is an address: either a number or a /regex/ */
245 if (isdigit(cmdstr[idx]) || cmdstr[idx] == '/')
246 idx = get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
248 /* second part (if present) will begin with a comma */
249 if (cmdstr[idx] == ',')
250 idx += get_address(&cmdstr[++idx], &sed_cmd->end_line, &sed_cmd->end_match);
252 /* last part (mandatory) will be a command */
253 if (cmdstr[idx] == '\0')
254 exit_sed(1, "sed: missing command\n");
255 if (!strchr("pds", cmdstr[idx])) /* <-- XXX add new commands here */
256 exit_sed(1, "sed: invalid command\n");
257 sed_cmd->cmd = cmdstr[idx];
258 /* special-case handling for 's' */
259 if (sed_cmd->cmd == 's') {
260 int oldidx, cflags = REG_NEWLINE;
262 /* format for substitution is:
268 /* verify that we have an 's' followed by a 'slash' */
269 if (cmdstr[++idx] != '/')
270 exit_sed(1, "sed: bad format in substitution expression\n");
272 /* save the match string */
274 idx = index_of_next_unescaped_slash(idx, cmdstr);
276 exit_sed(1, "sed: bad format in substitution expression\n");
277 match = strdup_substr(cmdstr, oldidx, idx);
279 /* save the replacement string */
281 idx = index_of_next_unescaped_slash(idx, cmdstr);
283 exit_sed(1, "sed: bad format in substitution expression\n");
284 sed_cmd->replace = strdup_substr(cmdstr, oldidx, idx);
286 /* process the flags */
287 while (cmdstr[++idx]) {
288 switch (cmdstr[idx]) {
296 exit_sed(1, "sed: bad option in substitution expression\n");
300 /* compile the regex */
301 sed_cmd->sub_match = (regex_t *)xmalloc(sizeof(regex_t));
302 if (bb_regcomp(sed_cmd->sub_match, match, cflags) != 0) {
310 static void add_cmd_str(const char *cmdstr)
312 char *my_cmdstr = trim_str(cmdstr);
314 /* if this is a comment, don't even bother */
315 if (my_cmdstr[0] == '#') {
321 sed_cmds = realloc(sed_cmds, sizeof(struct sed_cmd) * (++ncmds));
322 /* zero new element */
323 memset(&sed_cmds[ncmds-1], 0, sizeof(struct sed_cmd));
324 /* load command string into new array element */
325 parse_cmd_str(&sed_cmds[ncmds-1], my_cmdstr);
329 static void load_cmd_file(char *filename)
334 cmdfile = fopen(filename, "r");
336 exit_sed(1, strerror(errno));
338 while ((line = get_line_from_file(cmdfile)) != NULL) {
339 line[strlen(line)-1] = 0; /* eat newline */
346 static int do_sed_command(const struct sed_cmd *sed_cmd, const char *line)
350 switch (sed_cmd->cmd) {
360 case 's': /* oo, a fun one :-) */
362 /* we only substitute if the substitution 'search' expression matches */
363 if (regexec(sed_cmd->sub_match, line, 0, NULL, 0) == 0) {
366 char *ptr = (char *)line;
369 /* if we can match the search string... */
370 if (regexec(sed_cmd->sub_match, ptr, 1, ®match, 0) == 0) {
371 /* print everything before the match, */
372 for (i = 0; i < regmatch.rm_so; i++)
373 fputc(ptr[i], stdout);
374 /* then print the substitution in its place */
375 fputs(sed_cmd->replace, stdout);
376 /* then advance past the match */
377 ptr += regmatch.rm_eo;
378 /* and let the calling function know that something
379 * has been changed */
382 /* if we're not doing this globally... */
386 /* if we COULD NOT match the search string (meaning we've gone past
387 * all previous instances), get out */
392 /* is there anything left to print? */
403 static void process_file(FILE *file)
406 static int linenum = 0; /* GNU sed does not restart counting lines at EOF */
407 unsigned int still_in_range = 0;
411 /* go through every line in the file */
412 while ((line = get_line_from_file(file)) != NULL) {
417 /* for every line, go through all the commands */
418 for (i = 0; i < ncmds; i++) {
420 /* are we acting on a range of matched lines? */
421 if (sed_cmds[i].beg_match && sed_cmds[i].end_match) {
422 if (still_in_range || regexec(sed_cmds[i].beg_match, line, 0, NULL, 0) == 0) {
423 line_altered += do_sed_command(&sed_cmds[i], line);
425 if (regexec(sed_cmds[i].end_match, line, 0, NULL, 0) == 0)
430 /* are we trying to match a single line? */
431 else if (sed_cmds[i].beg_match) {
432 if (regexec(sed_cmds[i].beg_match, line, 0, NULL, 0) == 0)
433 line_altered += do_sed_command(&sed_cmds[i], line);
436 /* are we acting on a range of line numbers? */
437 else if (sed_cmds[i].beg_line > 0 && sed_cmds[i].end_line > 0) {
438 if (linenum >= sed_cmds[i].beg_line && linenum <= sed_cmds[i].end_line)
439 line_altered += do_sed_command(&sed_cmds[i], line);
442 /* are we acting on a specified line number */
443 else if (sed_cmds[i].beg_line > 0) {
444 if (linenum == sed_cmds[i].beg_line)
445 line_altered += do_sed_command(&sed_cmds[i], line);
448 /* not acting on matches or line numbers. act on every line */
450 line_altered += do_sed_command(&sed_cmds[i], line);
454 /* we will print the line unless we were told to be quiet or if the
455 * line was altered (via a 'd'elete or 's'ubstitution) */
456 if (!be_quiet && !line_altered)
463 extern int sed_main(int argc, char **argv)
467 /* do special-case option parsing */
468 if (argv[1] && (strcmp(argv[1], "--help") == 0))
471 /* do normal option parsing */
472 while ((opt = getopt(argc, argv, "Vhne:f:")) > 0) {
475 printf("Print Busybox version here\n");
488 load_cmd_file(optarg);
493 /* if we didn't get a pattern from a -e and no command file was specified,
494 * argv[optind] should be the pattern. no pattern, no worky */
496 if (argv[optind] == NULL)
499 add_cmd_str(argv[optind]);
505 /* argv[(optind)..(argc-1)] should be names of file to process. If no
506 * files were specified or '-' was specified, take input from stdin.
507 * Otherwise, we process all the files specified. */
508 if (argv[optind] == NULL || (strcmp(argv[optind], "-") == 0)) {
514 for (i = optind; i < argc; i++) {
515 file = fopen(argv[i], "r");
517 fprintf(stderr, "sed: %s: %s\n", argv[i], strerror(errno));