21f8681670251f25c3c8945af53fccfc7166360c
[oweals/busybox.git] / sed.c
1 /*
2  * sed.c - very minimalist version of sed
3  *
4  * Copyright (C) 1999,2000 by Lineo, inc.
5  * Written by Mark Whitley <markw@lineo.com>, <markw@enol.com>
6  *
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.
11  *
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.
16  *
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
20  *
21  */
22
23 /*
24         Supported features and commands in this version of sed:
25
26          - comments ('#')
27          - Address matching: num|/matchstr/[,num|/matchstr/|$]command
28          - Commands: p, d, s/match/replace/[g]
29          
30          (Note: Specifying an address (range) to match is *optional*; commands
31          default to the whole pattern space if no specific address match was
32          requested.)
33
34         Unsupported features:
35
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.
41
42 */
43
44 #include <stdio.h>
45 #include <stdlib.h> /* for realloc() */
46 #include <unistd.h> /* for getopt() */
47 #include <regex.h>
48 #include <string.h> /* for strdup() */
49 #include <errno.h>
50 #include <ctype.h> /* for isspace() */
51 #include "internal.h"
52
53
54 /* externs */
55 extern int optind; /* in unistd.h */
56 extern char *optarg; /* ditto */
57
58 /* options */
59 static int be_quiet = 0;
60
61 struct sed_cmd {
62
63         /* address storage */
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' */
68
69         /* the command */
70         char cmd; /* p,d,s (add more at your leisure :-) */
71
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) */
76 };
77
78 /* globals */
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 */
81
82 /*static char *cur_file = NULL;*/ /* file currently being processed XXX: do I need this? */
83
84 static const char sed_usage[] =
85         "sed [-Vhnef] pattern [files...]\n"
86 #ifndef BB_FEATURE_TRIVIAL_HELP
87         "\n"
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"
93         "\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"
97 #endif
98         ;
99
100 #if 0
101 static void destroy_cmd_strs()
102 {
103         if (sed_cmds == NULL)
104                 return;
105
106         /* destroy all the elements in the array */
107         while (--ncmds >= 0) {
108
109                 if (sed_cmds[ncmds].beg_match) {
110                         regfree(sed_cmds[ncmds].beg_match);
111                         free(sed_cmds[ncmds].beg_match);
112                 }
113                 if (sed_cmds[ncmds].end_match) {
114                         regfree(sed_cmds[ncmds].end_match);
115                         free(sed_cmds[ncmds].end_match);
116                 }
117                 if (sed_cmds[ncmds].sub_match) {
118                         regfree(sed_cmds[ncmds].sub_match);
119                         free(sed_cmds[ncmds].sub_match);
120                 }
121                 if (sed_cmds[ncmds].replace)
122                         free(sed_cmds[ncmds].replace);
123         }
124
125         /* destroy the array */
126         free(sed_cmds);
127         sed_cmds = NULL;
128 }
129 #endif
130
131 /*
132  * trim_str - trims leading and trailing space from a string
133  * 
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.
136  */
137 static char *trim_str(const char *str)
138 {
139         int i;
140         char *retstr = strdup(str);
141
142         /* trim leading whitespace */
143         memmove(retstr, &retstr[strspn(retstr, " \n\t\v")], strlen(retstr));
144
145         /* trim trailing whitespace */
146         i = strlen(retstr) - 1;
147         while (isspace(retstr[i]))
148                 i--;
149         retstr[++i] = 0;
150
151         /* Aside: 
152          *
153          * you know, a strrspn() would really be nice cuz then we could say:
154          * 
155          * retstr[strlen(retstr) - strrspn(retstr, " \n\t\v") + 1] = 0;
156          */
157         
158         return retstr;
159 }
160
161 /*
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.
164  */
165 static int index_of_next_unescaped_slash(int idx, const char *str)
166 {
167         do {
168                 idx++;
169                 /* test if we've hit the end */
170                 if (str[idx] == 0)
171                         return -1;
172         } while (str[idx] != '/' && str[idx - 1] != '\\');
173
174         return idx;
175 }
176
177 /*
178  * returns the index in the string just past where the address ends.
179  */
180 static int get_address(const char *str, int *line, regex_t **regex)
181 {
182         char *my_str = strdup(str);
183         int idx = 0;
184
185         if (isdigit(my_str[idx])) {
186                 do {
187                         idx++;
188                 } while (isdigit(my_str[idx]));
189                 my_str[idx] = 0;
190                 *line = atoi(my_str);
191                 *regex = NULL;
192         }
193         else if (my_str[idx] == '$') {
194                 *line = -1;
195                 *regex = NULL;
196                 idx++;
197         }
198         else if (my_str[idx] == '/') {
199                 idx = index_of_next_unescaped_slash(idx, my_str);
200                 if (idx == -1)
201                         fatalError("unterminated match expression\n");
202                 my_str[idx] = '\0';
203                 *regex = (regex_t *)xmalloc(sizeof(regex_t));
204                 xregcomp(*regex, my_str+1, REG_NEWLINE);
205         }
206         else {
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");
209                 idx = -1;
210         }
211
212         free(my_str);
213         return idx;
214 }
215
216 static char *strdup_substr(const char *str, int start, int end)
217 {
218         int size = end - start + 1;
219         char *newstr = xmalloc(size);
220         memcpy(newstr, str+start, size-1);
221         newstr[size-1] = '\0';
222         return newstr;
223 }
224
225 static void parse_cmd_str(struct sed_cmd *sed_cmd, const char *cmdstr)
226 {
227         int idx = 0;
228
229         /* parse the command
230          * format is: [addr][,addr]cmd
231          *            |----||-----||-|
232          *            part1 part2  part3
233          */
234
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);
238
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);
242
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;
252                 char *match;
253                 /* format for substitution is:
254                  *    s/match/replace/gI
255                  *    |               ||
256                  *    mandatory       optional
257                  */
258
259                 /* verify that we have an 's' followed by a 'slash' */
260                 if (cmdstr[++idx] != '/')
261                         fatalError("bad format in substitution expression\n");
262
263                 /* save the match string */
264                 oldidx = idx+1;
265                 idx = index_of_next_unescaped_slash(idx, cmdstr);
266                 if (idx == -1)
267                         fatalError("bad format in substitution expression\n");
268                 match = strdup_substr(cmdstr, oldidx, idx);
269
270                 /* save the replacement string */
271                 oldidx = idx+1;
272                 idx = index_of_next_unescaped_slash(idx, cmdstr);
273                 if (idx == -1)
274                         fatalError("bad format in substitution expression\n");
275                 sed_cmd->replace = strdup_substr(cmdstr, oldidx, idx);
276
277                 /* process the flags */
278                 while (cmdstr[++idx]) {
279                         switch (cmdstr[idx]) {
280                         case 'g':
281                                 sed_cmd->sub_g = 1;
282                                 break;
283                         case 'I':
284                                 cflags |= REG_ICASE;
285                                 break;
286                         default:
287                                 fatalError("bad option in substitution expression\n");
288                         }
289                 }
290                         
291                 /* compile the regex */
292                 sed_cmd->sub_match = (regex_t *)xmalloc(sizeof(regex_t));
293                 xregcomp(sed_cmd->sub_match, match, cflags);
294                 free(match);
295         }
296 }
297
298 static void add_cmd_str(const char *cmdstr)
299 {
300         char *my_cmdstr = trim_str(cmdstr);
301
302         /* if this is a comment, don't even bother */
303         if (my_cmdstr[0] == '#') {
304                 free(my_cmdstr);
305                 return;
306         }
307
308         /* grow the array */
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);
314 }
315
316
317 static void load_cmd_file(char *filename)
318 {
319         FILE *cmdfile;
320         char *line;
321
322         cmdfile = fopen(filename, "r");
323         if (cmdfile == NULL)
324                 fatalError(strerror(errno));
325
326         while ((line = get_line_from_file(cmdfile)) != NULL) {
327                 line[strlen(line)-1] = 0; /* eat newline */
328                 add_cmd_str(line);
329                 free(line);
330         }
331 }
332
333
334 static int do_sed_command(const struct sed_cmd *sed_cmd, const char *line) 
335 {
336         int altered = 0;
337
338         switch (sed_cmd->cmd) {
339
340                 case 'p':
341                         fputs(line, stdout);
342                         break;
343
344                 case 'd':
345                         altered++;
346                         break;
347
348                 case 's': /* oo, a fun one :-) */
349
350                         /* we only substitute if the substitution 'search' expression matches */
351                         if (regexec(sed_cmd->sub_match, line, 0, NULL, 0) == 0) {
352                                 regmatch_t regmatch;
353                                 int i;
354                                 char *ptr = (char *)line;
355
356                                 while (*ptr) {
357                                         /* if we can match the search string... */
358                                         if (regexec(sed_cmd->sub_match, ptr, 1, &regmatch, 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 */
368                                                 altered++;
369
370                                                 /* if we're not doing this globally... */
371                                                 if (!sed_cmd->sub_g)
372                                                         break;
373                                         }
374                                         /* if we COULD NOT match the search string (meaning we've gone past
375                                          * all previous instances), get out */
376                                         else
377                                                 break;
378                                 }
379
380                                 /* is there anything left to print? */
381                                 if (*ptr) 
382                                         fputs(ptr, stdout);
383                         }
384
385                         break;
386         }
387
388         return altered;
389 }
390
391 static void process_file(FILE *file)
392 {
393         char *line = NULL;
394         static int linenum = 0; /* GNU sed does not restart counting lines at EOF */
395         unsigned int still_in_range = 0;
396         int line_altered;
397         int i;
398
399         /* go through every line in the file */
400         while ((line = get_line_from_file(file)) != NULL) {
401
402                 linenum++;
403                 line_altered = 0;
404
405                 /* for every line, go through all the commands */
406                 for (i = 0; i < ncmds; i++) {
407
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);
412                                         still_in_range = 1; 
413                                         if (regexec(sed_cmds[i].end_match, line, 0, NULL, 0) == 0)
414                                                 still_in_range = 0;
415                                 }
416                         }
417
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);
422                         }
423
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);
428                         }
429
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);
434                         }
435
436                         /* not acting on matches or line numbers. act on every line */
437                         else 
438                                 line_altered += do_sed_command(&sed_cmds[i], line);
439
440                 }
441
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)
445                         fputs(line, stdout);
446
447                 free(line);
448         }
449 }
450
451 extern int sed_main(int argc, char **argv)
452 {
453         int opt;
454
455         /* do special-case option parsing */
456         if (argv[1] && (strcmp(argv[1], "--help") == 0))
457                 usage(sed_usage);
458
459 #if 0
460         /* destroy command strings on exit */
461         if (atexit(destroy_cmd_strs) == -1) {
462                 perror("sed");
463                 exit(1);
464         }
465 #endif
466
467         /* do normal option parsing */
468         while ((opt = getopt(argc, argv, "Vhne:f:")) > 0) {
469                 switch (opt) {
470                         case 'V':
471                                 printf("Print Busybox version here\n");
472                                 exit(0);
473                                 break;
474                         case 'h':
475                                 usage(sed_usage);
476                                 break;
477                         case 'n':
478                                 be_quiet++;
479                                 break;
480                         case 'e':
481                                 add_cmd_str(optarg);
482                                 break;
483                         case 'f': 
484                                 load_cmd_file(optarg);
485                                 break;
486                 }
487         }
488
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 */
491         if (ncmds == 0) {
492                 if (argv[optind] == NULL)
493                         usage(sed_usage);
494                 else {
495                         add_cmd_str(argv[optind]);
496                         optind++;
497                 }
498         }
499
500
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)) {
505                 process_file(stdin);
506         }
507         else {
508                 int i;
509                 FILE *file;
510                 for (i = optind; i < argc; i++) {
511                         file = fopen(argv[i], "r");
512                         if (file == NULL) {
513                                 fprintf(stderr, "sed: %s: %s\n", argv[i], strerror(errno));
514                         } else {
515                                 process_file(file);
516                                 fclose(file);
517                         }
518                 }
519         }
520         
521         return 0;
522 }