blob: 0e0d7f58c46e5f4d430828d3562bfe36c7e4f238 [file] [log] [blame]
Eric Andersen6b6b3f61999-10-28 16:06:25 +00001/*
Mark Whitley6315ce62000-07-10 22:55:51 +00002 * sed.c - very minimalist version of sed
Eric Andersen6b6b3f61999-10-28 16:06:25 +00003 *
Erik Andersen61677fe2000-04-13 01:18:56 +00004 * Copyright (C) 1999,2000 by Lineo, inc.
Mark Whitley6315ce62000-07-10 22:55:51 +00005 * Written by Mark Whitley <markw@lineo.com>, <markw@enol.com>
Erik Andersen1266a131999-12-29 22:19:46 +00006 *
Eric Andersen6b6b3f61999-10-28 16:06:25 +00007 * 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
Mark Whitley6315ce62000-07-10 22:55:51 +000023/*
24 Supported features and commands in this version of sed:
25
26 - comments ('#')
Mark Whitley94074a92000-07-14 00:00:15 +000027 - 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
Mark Whitley97562bd2000-07-17 20:06:42 +000030 - backreferences in substitution expressions (\1, \2...\9)
Mark Whitley6315ce62000-07-10 22:55:51 +000031
32 (Note: Specifying an address (range) to match is *optional*; commands
33 default to the whole pattern space if no specific address match was
34 requested.)
35
36 Unsupported features:
37
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.
43
44*/
45
Eric Andersen6b6b3f61999-10-28 16:06:25 +000046#include <stdio.h>
Mark Whitley6315ce62000-07-10 22:55:51 +000047#include <unistd.h> /* for getopt() */
48#include <regex.h>
49#include <string.h> /* for strdup() */
Eric Andersen6b6b3f61999-10-28 16:06:25 +000050#include <errno.h>
Mark Whitley6315ce62000-07-10 22:55:51 +000051#include <ctype.h> /* for isspace() */
52#include "internal.h"
53
Pavel Roskin9c5fcc32000-07-17 23:45:12 +000054#define bb_need_full_version
55#define BB_DECLARE_EXTERN
56#include "messages.c"
Mark Whitley6315ce62000-07-10 22:55:51 +000057
58/* externs */
59extern int optind; /* in unistd.h */
60extern char *optarg; /* ditto */
61
62/* options */
63static int be_quiet = 0;
64
Mark Whitley0e4cec02000-08-21 21:29:20 +000065static const int SUB_G = 1 << 0;
66#ifdef BB_FEATURE_SED_PATTERN_SPACE
67static const int SUB_P = 1 << 1;
68#endif
69
Mark Whitley6315ce62000-07-10 22:55:51 +000070struct sed_cmd {
71
72 /* address storage */
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' */
77
78 /* the command */
79 char cmd; /* p,d,s (add more at your leisure :-) */
80
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? */
Mark Whitley97562bd2000-07-17 20:06:42 +000084 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 */
Mark Whitley0e4cec02000-08-21 21:29:20 +000087#ifndef BB_FEATURE_SED_PATTERN_SPACE
88 unsigned int sub_flags:1; /* sed -e 's/foo/bar/g' (global) */
89#else
90 unsigned int sub_flags:2; /* sed -e 's/foo/bar/gp' (global/pattern) */
91#endif
Mark Whitley94074a92000-07-14 00:00:15 +000092
93 /* edit command (a,i,c) speicific field */
94 char *editline;
Mark Whitley6315ce62000-07-10 22:55:51 +000095};
96
97/* globals */
98static struct sed_cmd *sed_cmds = NULL; /* growable arrary holding a sequence of sed cmds */
99static int ncmds = 0; /* number of sed commands */
100
101/*static char *cur_file = NULL;*/ /* file currently being processed XXX: do I need this? */
Eric Andersen6b6b3f61999-10-28 16:06:25 +0000102
Eric Andersenb040d4f2000-07-25 18:01:20 +0000103#ifdef BB_FEATURE_CLEAN_UP
Mark Whitley6315ce62000-07-10 22:55:51 +0000104static void destroy_cmd_strs()
105{
106 if (sed_cmds == NULL)
107 return;
108
109 /* destroy all the elements in the array */
110 while (--ncmds >= 0) {
111
112 if (sed_cmds[ncmds].beg_match) {
113 regfree(sed_cmds[ncmds].beg_match);
114 free(sed_cmds[ncmds].beg_match);
Erik Andersene49d5ec2000-02-08 19:58:47 +0000115 }
Mark Whitley6315ce62000-07-10 22:55:51 +0000116 if (sed_cmds[ncmds].end_match) {
117 regfree(sed_cmds[ncmds].end_match);
118 free(sed_cmds[ncmds].end_match);
119 }
120 if (sed_cmds[ncmds].sub_match) {
121 regfree(sed_cmds[ncmds].sub_match);
122 free(sed_cmds[ncmds].sub_match);
123 }
124 if (sed_cmds[ncmds].replace)
125 free(sed_cmds[ncmds].replace);
126 }
Erik Andersene49d5ec2000-02-08 19:58:47 +0000127
Mark Whitley6315ce62000-07-10 22:55:51 +0000128 /* destroy the array */
129 free(sed_cmds);
130 sed_cmds = NULL;
131}
Mark Whitleyc41e8c82000-07-12 23:35:21 +0000132#endif
Mark Whitley6315ce62000-07-10 22:55:51 +0000133
Mark Whitley70705d72000-07-14 19:06:30 +0000134#if 0
Mark Whitley6315ce62000-07-10 22:55:51 +0000135/*
136 * trim_str - trims leading and trailing space from a string
137 *
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.
Mark Whitley70705d72000-07-14 19:06:30 +0000140 * XXX: This is now obsolete. Maybe it belongs nowhere.
Mark Whitley6315ce62000-07-10 22:55:51 +0000141 */
142static char *trim_str(const char *str)
143{
144 int i;
145 char *retstr = strdup(str);
146
147 /* trim leading whitespace */
148 memmove(retstr, &retstr[strspn(retstr, " \n\t\v")], strlen(retstr));
149
150 /* trim trailing whitespace */
151 i = strlen(retstr) - 1;
152 while (isspace(retstr[i]))
153 i--;
154 retstr[++i] = 0;
155
156 /* Aside:
157 *
158 * you know, a strrspn() would really be nice cuz then we could say:
159 *
Mark Whitley70705d72000-07-14 19:06:30 +0000160 * retstr[strrspn(retstr, " \n\t\v") + 1] = 0;
Mark Whitley6315ce62000-07-10 22:55:51 +0000161 */
162
163 return retstr;
164}
Mark Whitley70705d72000-07-14 19:06:30 +0000165#endif
166
167#if 0
168/*
169 * strrspn - works just like strspn() but goes from right to left instead of
170 * left to right
171 */
172static size_t strrspn(const char *s, const char *accept)
173{
174 size_t i = strlen(s);
175
176 while (strchr(accept, s[--i]))
177 ;
178
179 return i;
180}
181#endif
Mark Whitley6315ce62000-07-10 22:55:51 +0000182
183/*
Mark Whitley97562bd2000-07-17 20:06:42 +0000184 * 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 ('\').
Mark Whitley6315ce62000-07-10 22:55:51 +0000187 */
Mark Whitley06f35292000-07-13 19:58:04 +0000188static int index_of_next_unescaped_slash(const char *str, int idx)
Mark Whitley6315ce62000-07-10 22:55:51 +0000189{
Mark Whitley97562bd2000-07-17 20:06:42 +0000190 for ( ; str[idx]; idx++) {
191 if (str[idx] == '/' && str[idx-1] != '\\')
192 return idx;
193 }
Mark Whitley6315ce62000-07-10 22:55:51 +0000194
Mark Whitley97562bd2000-07-17 20:06:42 +0000195 /* if we make it to here, we've hit the end of the string */
196 return -1;
Mark Whitley6315ce62000-07-10 22:55:51 +0000197}
198
199/*
200 * returns the index in the string just past where the address ends.
201 */
202static int get_address(const char *str, int *line, regex_t **regex)
203{
204 char *my_str = strdup(str);
205 int idx = 0;
206
207 if (isdigit(my_str[idx])) {
208 do {
209 idx++;
210 } while (isdigit(my_str[idx]));
211 my_str[idx] = 0;
212 *line = atoi(my_str);
Mark Whitley6315ce62000-07-10 22:55:51 +0000213 }
214 else if (my_str[idx] == '$') {
215 *line = -1;
Mark Whitley6315ce62000-07-10 22:55:51 +0000216 idx++;
217 }
218 else if (my_str[idx] == '/') {
Mark Whitley97562bd2000-07-17 20:06:42 +0000219 idx = index_of_next_unescaped_slash(my_str, ++idx);
Mark Whitleydf5f6ba2000-07-11 16:53:56 +0000220 if (idx == -1)
Matt Kraaibe84cd42000-07-12 17:02:35 +0000221 fatalError("unterminated match expression\n");
Mark Whitleydf5f6ba2000-07-11 16:53:56 +0000222 my_str[idx] = '\0';
223 *regex = (regex_t *)xmalloc(sizeof(regex_t));
Mark Whitleyc41e8c82000-07-12 23:35:21 +0000224 xregcomp(*regex, my_str+1, REG_NEWLINE);
Mark Whitley496e33f2000-07-13 22:52:02 +0000225 idx++; /* so it points to the next character after the last '/' */
Mark Whitley6315ce62000-07-10 22:55:51 +0000226 }
227 else {
Matt Kraaid537a952000-07-14 01:51:25 +0000228 errorMsg("get_address: no address found in string\n"
229 "\t(you probably didn't check the string you passed me)\n");
Mark Whitley6315ce62000-07-10 22:55:51 +0000230 idx = -1;
231 }
Erik Andersene49d5ec2000-02-08 19:58:47 +0000232
Mark Whitley6315ce62000-07-10 22:55:51 +0000233 free(my_str);
234 return idx;
235}
Erik Andersene49d5ec2000-02-08 19:58:47 +0000236
Mark Whitleydf5f6ba2000-07-11 16:53:56 +0000237static char *strdup_substr(const char *str, int start, int end)
238{
239 int size = end - start + 1;
240 char *newstr = xmalloc(size);
241 memcpy(newstr, str+start, size-1);
242 newstr[size-1] = '\0';
243 return newstr;
244}
245
Mark Whitley70705d72000-07-14 19:06:30 +0000246static int parse_subst_cmd(struct sed_cmd *sed_cmd, const char *substr)
Mark Whitley06f35292000-07-13 19:58:04 +0000247{
248 int oldidx, cflags = REG_NEWLINE;
249 char *match;
250 int idx = 0;
Mark Whitley97562bd2000-07-17 20:06:42 +0000251 int j;
Mark Whitley06f35292000-07-13 19:58:04 +0000252
253 /*
254 * the string that gets passed to this function should look like this:
Mark Whitley0e4cec02000-08-21 21:29:20 +0000255 * s/match/replace/gIp
256 * || | |||
Mark Whitley06f35292000-07-13 19:58:04 +0000257 * mandatory optional
258 *
259 * (all three of the '/' slashes are mandatory)
260 */
261
262 /* verify that the 's' is followed by a 'slash' */
263 if (substr[++idx] != '/')
264 fatalError("bad format in substitution expression\n");
265
266 /* save the match string */
267 oldidx = idx+1;
Mark Whitley97562bd2000-07-17 20:06:42 +0000268 idx = index_of_next_unescaped_slash(substr, ++idx);
Mark Whitley06f35292000-07-13 19:58:04 +0000269 if (idx == -1)
270 fatalError("bad format in substitution expression\n");
271 match = strdup_substr(substr, oldidx, idx);
272
Mark Whitley97562bd2000-07-17 20:06:42 +0000273 /* 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 */
277
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++;
283 }
284
Mark Whitley06f35292000-07-13 19:58:04 +0000285 /* save the replacement string */
286 oldidx = idx+1;
Mark Whitley97562bd2000-07-17 20:06:42 +0000287 idx = index_of_next_unescaped_slash(substr, ++idx);
Mark Whitley06f35292000-07-13 19:58:04 +0000288 if (idx == -1)
289 fatalError("bad format in substitution expression\n");
290 sed_cmd->replace = strdup_substr(substr, oldidx, idx);
291
292 /* process the flags */
293 while (substr[++idx]) {
294 switch (substr[idx]) {
Mark Whitley70705d72000-07-14 19:06:30 +0000295 case 'g':
Mark Whitley0e4cec02000-08-21 21:29:20 +0000296 sed_cmd->sub_flags = SUB_G;
Mark Whitley70705d72000-07-14 19:06:30 +0000297 break;
298 case 'I':
299 cflags |= REG_ICASE;
300 break;
Mark Whitley0e4cec02000-08-21 21:29:20 +0000301#ifdef BB_FEATURE_SED_PATTERN_SPACE
302 case 'p':
303 sed_cmd->sub_flags = SUB_P;
304 break;
305#endif
Mark Whitley70705d72000-07-14 19:06:30 +0000306 default:
307 /* any whitespace or semicolon trailing after a s/// is ok */
308 if (strchr("; \t\v\n\r", substr[idx]))
309 goto out;
310 /* else */
311 fatalError("bad option in substitution expression\n");
Mark Whitley06f35292000-07-13 19:58:04 +0000312 }
313 }
Mark Whitley70705d72000-07-14 19:06:30 +0000314
315out:
Mark Whitley97562bd2000-07-17 20:06:42 +0000316 /* compile the match string into a regex */
Mark Whitley06f35292000-07-13 19:58:04 +0000317 sed_cmd->sub_match = (regex_t *)xmalloc(sizeof(regex_t));
318 xregcomp(sed_cmd->sub_match, match, cflags);
319 free(match);
Mark Whitley70705d72000-07-14 19:06:30 +0000320
321 return idx;
Mark Whitley06f35292000-07-13 19:58:04 +0000322}
323
Mark Whitley70705d72000-07-14 19:06:30 +0000324static int parse_edit_cmd(struct sed_cmd *sed_cmd, const char *editstr)
Mark Whitley94074a92000-07-14 00:00:15 +0000325{
326 int idx = 0;
Mark Whitley464c5de2000-07-14 23:24:00 +0000327 int slashes_eaten = 0;
Mark Whitley94074a92000-07-14 00:00:15 +0000328 char *ptr; /* shorthand */
329
330 /*
331 * the string that gets passed to this function should look like this:
332 *
333 * need one of these
334 * |
335 * | this backslash (immediately following the edit command) is mandatory
336 * | |
337 * [aic]\
338 * TEXT1\
339 * TEXT2\
340 * TEXTN
341 *
342 * as soon as we hit a TEXT line that has no trailing '\', we're done.
343 * this means a command like:
344 *
345 * i\
346 * INSERTME
347 *
348 * is a-ok.
349 *
350 */
351
352 if (editstr[1] != '\\' && (editstr[2] != '\n' || editstr[2] != '\r'))
353 fatalError("bad format in edit expression\n");
354
355 /* store the edit line text */
Mark Whitley34623db2000-07-14 00:49:59 +0000356 /* make editline big enough to accomodate the extra '\n' we will tack on
357 * to the end */
358 sed_cmd->editline = xmalloc(strlen(&editstr[3]) + 2);
359 strcpy(sed_cmd->editline, &editstr[3]);
Mark Whitley94074a92000-07-14 00:00:15 +0000360 ptr = sed_cmd->editline;
361
362 /* now we need to go through * and: s/\\[\r\n]$/\n/g on the edit line */
363 while (ptr[idx]) {
364 while (ptr[idx] != '\\' && (ptr[idx+1] != '\n' || ptr[idx+1] != '\r')) {
365 idx++;
366 if (!ptr[idx]) {
Mark Whitley464c5de2000-07-14 23:24:00 +0000367 goto out;
Mark Whitley94074a92000-07-14 00:00:15 +0000368 }
369 }
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;
Mark Whitley464c5de2000-07-14 23:24:00 +0000373 slashes_eaten++;
Mark Whitley94074a92000-07-14 00:00:15 +0000374 /* substitue \r for \n if needed */
375 if (ptr[idx] == '\r')
376 ptr[idx] = '\n';
377 }
Mark Whitley70705d72000-07-14 19:06:30 +0000378
Mark Whitley464c5de2000-07-14 23:24:00 +0000379out:
380 ptr[idx] = '\n';
381 ptr[idx+1] = 0;
382
383 /* this accounts for discrepancies between the modified string and the
384 * original string passed in to this function */
385 idx += slashes_eaten;
386
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) */
390
391 idx += 3;
392
Mark Whitley70705d72000-07-14 19:06:30 +0000393 return idx;
Mark Whitley94074a92000-07-14 00:00:15 +0000394}
395
Mark Whitley70705d72000-07-14 19:06:30 +0000396static char *parse_cmd_str(struct sed_cmd *sed_cmd, const char *cmdstr)
Mark Whitley6315ce62000-07-10 22:55:51 +0000397{
398 int idx = 0;
399
400 /* parse the command
401 * format is: [addr][,addr]cmd
402 * |----||-----||-|
403 * part1 part2 part3
404 */
405
Mark Whitley70705d72000-07-14 19:06:30 +0000406
Mark Whitley6315ce62000-07-10 22:55:51 +0000407 /* 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);
410
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);
414
415 /* last part (mandatory) will be a command */
416 if (cmdstr[idx] == '\0')
Matt Kraaibe84cd42000-07-12 17:02:35 +0000417 fatalError("missing command\n");
Mark Whitley94074a92000-07-14 00:00:15 +0000418 if (!strchr("pdsaic", cmdstr[idx])) /* <-- XXX add new commands here */
Matt Kraaibe84cd42000-07-12 17:02:35 +0000419 fatalError("invalid command\n");
Mark Whitley6315ce62000-07-10 22:55:51 +0000420 sed_cmd->cmd = cmdstr[idx];
Mark Whitley6315ce62000-07-10 22:55:51 +0000421
Mark Whitley06f35292000-07-13 19:58:04 +0000422 /* special-case handling for (s)ubstitution */
Mark Whitley70705d72000-07-14 19:06:30 +0000423 if (sed_cmd->cmd == 's') {
424 idx += parse_subst_cmd(sed_cmd, &cmdstr[idx]);
425 }
Mark Whitley94074a92000-07-14 00:00:15 +0000426 /* special-case handling for (a)ppend, (i)nsert, and (c)hange */
Mark Whitley70705d72000-07-14 19:06:30 +0000427 else if (strchr("aic", cmdstr[idx])) {
Mark Whitley02008342000-07-14 00:13:52 +0000428 if (sed_cmd->end_line || sed_cmd->end_match)
429 fatalError("only a beginning address can be specified for edit commands\n");
Mark Whitley70705d72000-07-14 19:06:30 +0000430 idx += parse_edit_cmd(sed_cmd, &cmdstr[idx]);
Mark Whitley02008342000-07-14 00:13:52 +0000431 }
Mark Whitley464c5de2000-07-14 23:24:00 +0000432 /* if it was a single-letter command (such as 'p' or 'd') we need to
433 * increment the index past that command */
434 else
435 idx++;
Mark Whitley70705d72000-07-14 19:06:30 +0000436
437 /* give back whatever's left over */
Mark Whitley464c5de2000-07-14 23:24:00 +0000438 return (char *)&cmdstr[idx];
Eric Andersen50d63601999-11-09 01:47:36 +0000439}
Eric Andersen6b6b3f61999-10-28 16:06:25 +0000440
Mark Whitley6315ce62000-07-10 22:55:51 +0000441static void add_cmd_str(const char *cmdstr)
Erik Andersen1266a131999-12-29 22:19:46 +0000442{
Mark Whitley70705d72000-07-14 19:06:30 +0000443 char *mystr = (char *)cmdstr;
Erik Andersen1266a131999-12-29 22:19:46 +0000444
Mark Whitley70705d72000-07-14 19:06:30 +0000445 do {
Mark Whitley6315ce62000-07-10 22:55:51 +0000446
Mark Whitley70705d72000-07-14 19:06:30 +0000447 /* 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
Mark Whitley464c5de2000-07-14 23:24:00 +0000450 * whitespace or a final / no-op semicolon. either way, get out */
Mark Whitley70705d72000-07-14 19:06:30 +0000451 if (strlen(mystr) == 0)
452 return;
453 /* if this is a comment, jump past it and keep going */
454 if (mystr[0] == '#') {
455 mystr = strpbrk(mystr, ";\n\r");
456 continue;
457 }
458 /* grow the array */
Matt Kraai322ae932000-09-13 02:46:14 +0000459 sed_cmds = xrealloc(sed_cmds, sizeof(struct sed_cmd) * (++ncmds));
Mark Whitley70705d72000-07-14 19:06:30 +0000460 /* 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);
464
Mark Whitley464c5de2000-07-14 23:24:00 +0000465 } while (mystr && strlen(mystr));
Mark Whitley6315ce62000-07-10 22:55:51 +0000466}
467
468
469static void load_cmd_file(char *filename)
470{
471 FILE *cmdfile;
472 char *line;
Mark Whitley94074a92000-07-14 00:00:15 +0000473 char *nextline;
Mark Whitley6315ce62000-07-10 22:55:51 +0000474
475 cmdfile = fopen(filename, "r");
476 if (cmdfile == NULL)
Mark Whitley858c1ad2000-07-11 21:38:47 +0000477 fatalError(strerror(errno));
Mark Whitley6315ce62000-07-10 22:55:51 +0000478
479 while ((line = get_line_from_file(cmdfile)) != NULL) {
Mark Whitley94074a92000-07-14 00:00:15 +0000480 /* 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) {
Matt Kraai322ae932000-09-13 02:46:14 +0000483 line = xrealloc(line, strlen(line) + strlen(nextline) + 1);
Mark Whitley94074a92000-07-14 00:00:15 +0000484 strcat(line, nextline);
Mark Whitley464c5de2000-07-14 23:24:00 +0000485 free(nextline);
Mark Whitley94074a92000-07-14 00:00:15 +0000486 }
Mark Whitley464c5de2000-07-14 23:24:00 +0000487 /* 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;
Mark Whitley6315ce62000-07-10 22:55:51 +0000491 add_cmd_str(line);
492 free(line);
493 }
494}
495
Mark Whitley97562bd2000-07-17 20:06:42 +0000496static void print_subst_w_backrefs(const char *line, const char *replace, regmatch_t *regmatch)
497{
498 int i;
499
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])) {
504 int j;
505 char tmpstr[2];
506 int backref;
507 ++i; /* i now indexes the backref number, instead of the leading slash */
508 tmpstr[0] = replace[i];
509 tmpstr[1] = 0;
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);
514 }
515
Mark Whitley83e85f62000-07-25 20:48:44 +0000516 /* if we find a backslash escaped character, print the character */
517 else if (replace[i] == '\\') {
518 ++i;
519 fputc(replace[i], stdout);
520 }
521
Mark Whitley97562bd2000-07-17 20:06:42 +0000522 /* 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
525 * purpose...) */
526 else if (replace[i] == '&' && replace[i-1] != '\\') {
527 int j;
528 for (j = regmatch[0].rm_so; j < regmatch[0].rm_eo; j++)
529 fputc(line[j], stdout);
530 }
531 /* nothing special, just print this char of the replacement string to stdout */
532 else
533 fputc(replace[i], stdout);
534 }
535}
536
Mark Whitley4f7fe772000-07-13 20:01:58 +0000537static int do_subst_command(const struct sed_cmd *sed_cmd, const char *line)
538{
539 int altered = 0;
540
541 /* we only substitute if the substitution 'search' expression matches */
542 if (regexec(sed_cmd->sub_match, line, 0, NULL, 0) == 0) {
Mark Whitley97562bd2000-07-17 20:06:42 +0000543 regmatch_t *regmatch = xmalloc(sizeof(regmatch_t) * (sed_cmd->num_backrefs+1));
Mark Whitley4f7fe772000-07-13 20:01:58 +0000544 int i;
545 char *ptr = (char *)line;
546
547 while (*ptr) {
548 /* if we can match the search string... */
Mark Whitley97562bd2000-07-17 20:06:42 +0000549 if (regexec(sed_cmd->sub_match, ptr, sed_cmd->num_backrefs+1, regmatch, 0) == 0) {
Mark Whitley4f7fe772000-07-13 20:01:58 +0000550 /* print everything before the match, */
Mark Whitley0e4cec02000-08-21 21:29:20 +0000551 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))
554#endif
Mark Whitley4f7fe772000-07-13 20:01:58 +0000555 fputc(ptr[i], stdout);
Mark Whitley0e4cec02000-08-21 21:29:20 +0000556 }
Mark Whitley97562bd2000-07-17 20:06:42 +0000557
Mark Whitley4f7fe772000-07-13 20:01:58 +0000558 /* then print the substitution in its place */
Mark Whitley0e4cec02000-08-21 21:29:20 +0000559#ifdef BB_FEATURE_SED_PATTERN_SPACE
560 if(!be_quiet || (sed_cmd->sub_flags & SUB_P))
561#endif
Mark Whitley97562bd2000-07-17 20:06:42 +0000562 print_subst_w_backrefs(ptr, sed_cmd->replace, regmatch);
563
Mark Whitley4f7fe772000-07-13 20:01:58 +0000564 /* then advance past the match */
Mark Whitley97562bd2000-07-17 20:06:42 +0000565 ptr += regmatch[0].rm_eo;
566
Mark Whitley94074a92000-07-14 00:00:15 +0000567 /* and flag that something has changed */
Mark Whitley4f7fe772000-07-13 20:01:58 +0000568 altered++;
569
570 /* if we're not doing this globally... */
Mark Whitley0e4cec02000-08-21 21:29:20 +0000571 if (!sed_cmd->sub_flags & SUB_G)
Mark Whitley4f7fe772000-07-13 20:01:58 +0000572 break;
573 }
574 /* if we COULD NOT match the search string (meaning we've gone past
575 * all previous instances), get out */
576 else
577 break;
578 }
579
580 /* is there anything left to print? */
Mark Whitley0e4cec02000-08-21 21:29:20 +0000581#ifdef BB_FEATURE_SED_PATTERN_SPACE
582 if (*ptr && (!be_quiet || sed_cmds->sub_flags & SUB_P))
583#else
Mark Whitley4f7fe772000-07-13 20:01:58 +0000584 if (*ptr)
Mark Whitley0e4cec02000-08-21 21:29:20 +0000585#endif
Mark Whitley4f7fe772000-07-13 20:01:58 +0000586 fputs(ptr, stdout);
Mark Whitley97562bd2000-07-17 20:06:42 +0000587
588 /* cleanup */
589 free(regmatch);
Mark Whitley4f7fe772000-07-13 20:01:58 +0000590 }
591
592 return altered;
593}
Mark Whitley6315ce62000-07-10 22:55:51 +0000594
595static int do_sed_command(const struct sed_cmd *sed_cmd, const char *line)
596{
597 int altered = 0;
598
599 switch (sed_cmd->cmd) {
600
601 case 'p':
602 fputs(line, stdout);
603 break;
604
605 case 'd':
606 altered++;
607 break;
608
Mark Whitley4f7fe772000-07-13 20:01:58 +0000609 case 's':
610 altered = do_subst_command(sed_cmd, line);
Mark Whitley6315ce62000-07-10 22:55:51 +0000611 break;
Mark Whitley94074a92000-07-14 00:00:15 +0000612
613 case 'a':
614 fputs(line, stdout);
615 fputs(sed_cmd->editline, stdout);
616 altered++;
617 break;
618
619 case 'i':
620 fputs(sed_cmd->editline, stdout);
621 break;
622
623 case 'c':
624 fputs(sed_cmd->editline, stdout);
625 altered++;
626 break;
Mark Whitley6315ce62000-07-10 22:55:51 +0000627 }
628
629 return altered;
630}
631
632static void process_file(FILE *file)
633{
634 char *line = NULL;
635 static int linenum = 0; /* GNU sed does not restart counting lines at EOF */
636 unsigned int still_in_range = 0;
637 int line_altered;
638 int i;
639
640 /* go through every line in the file */
641 while ((line = get_line_from_file(file)) != NULL) {
642
643 linenum++;
644 line_altered = 0;
645
646 /* for every line, go through all the commands */
647 for (i = 0; i < ncmds; i++) {
648
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);
653 still_in_range = 1;
654 if (regexec(sed_cmds[i].end_match, line, 0, NULL, 0) == 0)
655 still_in_range = 0;
656 }
657 }
658
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);
663 }
664
665 /* are we acting on a range of line numbers? */
Mark Whitley40406e62000-08-10 00:09:47 +0000666 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))
Mark Whitley6315ce62000-07-10 22:55:51 +0000668 line_altered += do_sed_command(&sed_cmds[i], line);
669 }
670
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);
675 }
676
677 /* not acting on matches or line numbers. act on every line */
678 else
679 line_altered += do_sed_command(&sed_cmds[i], line);
680
Erik Andersene49d5ec2000-02-08 19:58:47 +0000681 }
Erik Andersen1266a131999-12-29 22:19:46 +0000682
Mark Whitley0e4cec02000-08-21 21:29:20 +0000683 /* 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)
687#else
688 /* we where specificly requested to print the output */
689 if ((!be_quiet || (sed_cmds[i].sub_flags & SUB_P)) && !line_altered)
690#endif
Mark Whitley6315ce62000-07-10 22:55:51 +0000691 fputs(line, stdout);
692
693 free(line);
Erik Andersene49d5ec2000-02-08 19:58:47 +0000694 }
Erik Andersen1266a131999-12-29 22:19:46 +0000695}
696
697extern int sed_main(int argc, char **argv)
Eric Andersen6b6b3f61999-10-28 16:06:25 +0000698{
Mark Whitley6315ce62000-07-10 22:55:51 +0000699 int opt;
Eric Andersen6b6b3f61999-10-28 16:06:25 +0000700
Eric Andersenb040d4f2000-07-25 18:01:20 +0000701#ifdef BB_FEATURE_CLEAN_UP
Mark Whitley858c1ad2000-07-11 21:38:47 +0000702 /* destroy command strings on exit */
703 if (atexit(destroy_cmd_strs) == -1) {
704 perror("sed");
705 exit(1);
706 }
Mark Whitleyc41e8c82000-07-12 23:35:21 +0000707#endif
Mark Whitley858c1ad2000-07-11 21:38:47 +0000708
Mark Whitley6315ce62000-07-10 22:55:51 +0000709 /* do normal option parsing */
Mark Whitley1f45b262000-07-20 23:08:40 +0000710 while ((opt = getopt(argc, argv, "hne:f:")) > 0) {
Mark Whitley6315ce62000-07-10 22:55:51 +0000711 switch (opt) {
Mark Whitley6315ce62000-07-10 22:55:51 +0000712 case 'h':
713 usage(sed_usage);
714 break;
Erik Andersene916d242000-03-06 19:20:35 +0000715 case 'n':
Mark Whitley6315ce62000-07-10 22:55:51 +0000716 be_quiet++;
Erik Andersene916d242000-03-06 19:20:35 +0000717 break;
718 case 'e':
Mark Whitley6315ce62000-07-10 22:55:51 +0000719 add_cmd_str(optarg);
Erik Andersene916d242000-03-06 19:20:35 +0000720 break;
Mark Whitley6315ce62000-07-10 22:55:51 +0000721 case 'f':
722 load_cmd_file(optarg);
Erik Andersene49d5ec2000-02-08 19:58:47 +0000723 break;
Erik Andersene49d5ec2000-02-08 19:58:47 +0000724 }
Eric Andersen6b6b3f61999-10-28 16:06:25 +0000725 }
Mark Whitley6315ce62000-07-10 22:55:51 +0000726
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 */
729 if (ncmds == 0) {
730 if (argv[optind] == NULL)
731 usage(sed_usage);
732 else {
733 add_cmd_str(argv[optind]);
734 optind++;
735 }
736 }
737
738
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)) {
743 process_file(stdin);
744 }
745 else {
746 int i;
747 FILE *file;
748 for (i = optind; i < argc; i++) {
749 file = fopen(argv[i], "r");
750 if (file == NULL) {
Matt Kraaid537a952000-07-14 01:51:25 +0000751 errorMsg("%s: %s\n", argv[i], strerror(errno));
Mark Whitley6315ce62000-07-10 22:55:51 +0000752 } else {
753 process_file(file);
754 fclose(file);
755 }
756 }
757 }
758
Mark Whitley6315ce62000-07-10 22:55:51 +0000759 return 0;
Eric Andersen6b6b3f61999-10-28 16:06:25 +0000760}