sed.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * sed.c - very minimalist version of sed
  4. *
  5. * Copyright (C) 1999,2000,2001 by Lineo, inc. and Mark Whitley
  6. * Copyright (C) 1999,2000,2001 by Mark Whitley <markw@codepoet.org>
  7. * Copyright (C) 2002 Matt Kraai
  8. * Copyright (C) 2003 by Glenn McGrath
  9. * Copyright (C) 2003,2004 by Rob Landley <rob@landley.net>
  10. *
  11. * MAINTAINER: Rob Landley <rob@landley.net>
  12. *
  13. * Licensed under GPLv2, see file LICENSE in this source tree.
  14. */
  15. /* Code overview.
  16. *
  17. * Files are laid out to avoid unnecessary function declarations. So for
  18. * example, every function add_cmd calls occurs before add_cmd in this file.
  19. *
  20. * add_cmd() is called on each line of sed command text (from a file or from
  21. * the command line). It calls get_address() and parse_cmd_args(). The
  22. * resulting sed_cmd_t structures are appended to a linked list
  23. * (G.sed_cmd_head/G.sed_cmd_tail).
  24. *
  25. * process_files() does actual sedding, reading data lines from each input FILE*
  26. * (which could be stdin) and applying the sed command list (sed_cmd_head) to
  27. * each of the resulting lines.
  28. *
  29. * sed_main() is where external code calls into this, with a command line.
  30. */
  31. /* Supported features and commands in this version of sed:
  32. *
  33. * - comments ('#')
  34. * - address matching: num|/matchstr/[,num|/matchstr/|$]command
  35. * - commands: (p)rint, (d)elete, (s)ubstitue (with g & I flags)
  36. * - edit commands: (a)ppend, (i)nsert, (c)hange
  37. * - file commands: (r)ead
  38. * - backreferences in substitution expressions (\0, \1, \2...\9)
  39. * - grouped commands: {cmd1;cmd2}
  40. * - transliteration (y/source-chars/dest-chars/)
  41. * - pattern space hold space storing / swapping (g, h, x)
  42. * - labels / branching (: label, b, t, T)
  43. *
  44. * (Note: Specifying an address (range) to match is *optional*; commands
  45. * default to the whole pattern space if no specific address match was
  46. * requested.)
  47. *
  48. * Todo:
  49. * - Create a wrapper around regex to make libc's regex conform with sed
  50. *
  51. * Reference
  52. * http://www.opengroup.org/onlinepubs/007904975/utilities/sed.html
  53. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html
  54. * http://sed.sourceforge.net/sedfaq3.html
  55. */
  56. //config:config SED
  57. //config: bool "sed (12 kb)"
  58. //config: default y
  59. //config: help
  60. //config: sed is used to perform text transformations on a file
  61. //config: or input from a pipeline.
  62. //applet:IF_SED(APPLET(sed, BB_DIR_BIN, BB_SUID_DROP))
  63. //kbuild:lib-$(CONFIG_SED) += sed.o
  64. //usage:#define sed_trivial_usage
  65. //usage: "[-i[SFX]] [-nrE] [-f FILE]... [-e CMD]... [FILE]...\n"
  66. //usage: "or: sed [-i[SFX]] [-nrE] CMD [FILE]..."
  67. //usage:#define sed_full_usage "\n\n"
  68. //usage: " -e CMD Add CMD to sed commands to be executed"
  69. //usage: "\n -f FILE Add FILE contents to sed commands to be executed"
  70. //usage: "\n -i[SFX] Edit files in-place (otherwise sends to stdout)"
  71. //usage: "\n Optionally back files up, appending SFX"
  72. //usage: "\n -n Suppress automatic printing of pattern space"
  73. //usage: "\n -r,-E Use extended regex syntax"
  74. //usage: "\n"
  75. //usage: "\nIf no -e or -f, the first non-option argument is the sed command string."
  76. //usage: "\nRemaining arguments are input files (stdin if none)."
  77. //usage:
  78. //usage:#define sed_example_usage
  79. //usage: "$ echo \"foo\" | sed -e 's/f[a-zA-Z]o/bar/g'\n"
  80. //usage: "bar\n"
  81. #include "libbb.h"
  82. #include "common_bufsiz.h"
  83. #include "xregex.h"
  84. #if 0
  85. # define dbg(...) bb_error_msg(__VA_ARGS__)
  86. #else
  87. # define dbg(...) ((void)0)
  88. #endif
  89. enum {
  90. OPT_in_place = 1 << 0,
  91. };
  92. /* Each sed command turns into one of these structures. */
  93. typedef struct sed_cmd_s {
  94. /* Ordered by alignment requirements: currently 36 bytes on x86 */
  95. struct sed_cmd_s *next; /* Next command (linked list, NULL terminated) */
  96. /* address storage */
  97. regex_t *beg_match; /* sed -e '/match/cmd' */
  98. regex_t *end_match; /* sed -e '/match/,/end_match/cmd' */
  99. regex_t *sub_match; /* For 's/sub_match/string/' */
  100. int beg_line; /* 'sed 1p' 0 == apply commands to all lines */
  101. int beg_line_orig; /* copy of the above, needed for -i */
  102. int end_line; /* 'sed 1,3p' 0 == one line only. -1 = last line ($). -2-N = +N */
  103. int end_line_orig;
  104. FILE *sw_file; /* File (sw) command writes to, NULL for none. */
  105. char *string; /* Data string for (saicytb) commands. */
  106. unsigned which_match; /* (s) Which match to replace (0 for all) */
  107. /* Bitfields (gcc won't group them if we don't) */
  108. unsigned invert:1; /* the '!' after the address */
  109. unsigned in_match:1; /* Next line also included in match? */
  110. unsigned sub_p:1; /* (s) print option */
  111. char sw_last_char; /* Last line written by (sw) had no '\n' */
  112. /* GENERAL FIELDS */
  113. char cmd; /* The command char: abcdDgGhHilnNpPqrstwxy:={} */
  114. } sed_cmd_t;
  115. static const char semicolon_whitespace[] ALIGN1 = "; \n\r\t\v";
  116. struct globals {
  117. /* options */
  118. int be_quiet, regex_type;
  119. FILE *nonstdout;
  120. char *outname, *hold_space;
  121. smallint exitcode;
  122. /* list of input files */
  123. int current_input_file, last_input_file;
  124. char **input_file_list;
  125. FILE *current_fp;
  126. regmatch_t regmatch[10];
  127. regex_t *previous_regex_ptr;
  128. /* linked list of sed commands */
  129. sed_cmd_t *sed_cmd_head, **sed_cmd_tail;
  130. /* linked list of append lines */
  131. llist_t *append_head;
  132. char *add_cmd_line;
  133. struct pipeline {
  134. char *buf; /* Space to hold string */
  135. int idx; /* Space used */
  136. int len; /* Space allocated */
  137. } pipeline;
  138. } FIX_ALIASING;
  139. #define G (*(struct globals*)bb_common_bufsiz1)
  140. #define INIT_G() do { \
  141. setup_common_bufsiz(); \
  142. BUILD_BUG_ON(sizeof(G) > COMMON_BUFSIZE); \
  143. G.sed_cmd_tail = &G.sed_cmd_head; \
  144. } while (0)
  145. #if ENABLE_FEATURE_CLEAN_UP
  146. static void sed_free_and_close_stuff(void)
  147. {
  148. sed_cmd_t *sed_cmd = G.sed_cmd_head;
  149. llist_free(G.append_head, free);
  150. while (sed_cmd) {
  151. sed_cmd_t *sed_cmd_next = sed_cmd->next;
  152. if (sed_cmd->sw_file)
  153. fclose(sed_cmd->sw_file);
  154. if (sed_cmd->beg_match) {
  155. regfree(sed_cmd->beg_match);
  156. free(sed_cmd->beg_match);
  157. }
  158. if (sed_cmd->end_match) {
  159. regfree(sed_cmd->end_match);
  160. free(sed_cmd->end_match);
  161. }
  162. if (sed_cmd->sub_match) {
  163. regfree(sed_cmd->sub_match);
  164. free(sed_cmd->sub_match);
  165. }
  166. free(sed_cmd->string);
  167. free(sed_cmd);
  168. sed_cmd = sed_cmd_next;
  169. }
  170. free(G.hold_space);
  171. if (G.current_fp)
  172. fclose(G.current_fp);
  173. }
  174. #else
  175. void sed_free_and_close_stuff(void);
  176. #endif
  177. /* If something bad happens during -i operation, delete temp file */
  178. static void cleanup_outname(void)
  179. {
  180. if (G.outname) unlink(G.outname);
  181. }
  182. /* strcpy, replacing "\from" with 'to'. If to is NUL, replacing "\any" with 'any' */
  183. static unsigned parse_escapes(char *dest, const char *string, int len, char from, char to)
  184. {
  185. char *d = dest;
  186. int i = 0;
  187. if (len == -1)
  188. len = strlen(string);
  189. while (i < len) {
  190. if (string[i] == '\\') {
  191. if (!to || string[i+1] == from) {
  192. if ((*d = to ? to : string[i+1]) == '\0')
  193. return d - dest;
  194. i += 2;
  195. d++;
  196. continue;
  197. }
  198. i++; /* skip backslash in string[] */
  199. *d++ = '\\';
  200. /* fall through: copy next char verbatim */
  201. }
  202. if ((*d = string[i++]) == '\0')
  203. return d - dest;
  204. d++;
  205. }
  206. *d = '\0';
  207. return d - dest;
  208. }
  209. static char *copy_parsing_escapes(const char *string, int len)
  210. {
  211. const char *s;
  212. char *dest = xmalloc(len + 1);
  213. /* sed recognizes \n */
  214. /* GNU sed also recognizes \t and \r */
  215. for (s = "\nn\tt\rr"; *s; s += 2) {
  216. len = parse_escapes(dest, string, len, s[1], s[0]);
  217. string = dest;
  218. }
  219. return dest;
  220. }
  221. /*
  222. * index_of_next_unescaped_regexp_delim - walks left to right through a string
  223. * beginning at a specified index and returns the index of the next regular
  224. * expression delimiter (typically a forward slash ('/')) not preceded by
  225. * a backslash ('\'). A negative delimiter disables square bracket checking.
  226. */
  227. static int index_of_next_unescaped_regexp_delim(int delimiter, const char *str)
  228. {
  229. int bracket = -1;
  230. int escaped = 0;
  231. int idx = 0;
  232. char ch;
  233. if (delimiter < 0) {
  234. bracket--;
  235. delimiter = -delimiter;
  236. }
  237. for (; (ch = str[idx]) != '\0'; idx++) {
  238. if (bracket >= 0) {
  239. if (ch == ']'
  240. && !(bracket == idx - 1 || (bracket == idx - 2 && str[idx - 1] == '^'))
  241. ) {
  242. bracket = -1;
  243. }
  244. } else if (escaped)
  245. escaped = 0;
  246. else if (ch == '\\')
  247. escaped = 1;
  248. else if (bracket == -1 && ch == '[')
  249. bracket = idx;
  250. else if (ch == delimiter)
  251. return idx;
  252. }
  253. /* if we make it to here, we've hit the end of the string */
  254. bb_error_msg_and_die("unmatched '%c'", delimiter);
  255. }
  256. /*
  257. * Returns the index of the third delimiter
  258. */
  259. static int parse_regex_delim(const char *cmdstr, char **match, char **replace)
  260. {
  261. const char *cmdstr_ptr = cmdstr;
  262. unsigned char delimiter;
  263. int idx = 0;
  264. /* verify that the 's' or 'y' is followed by something. That something
  265. * (typically a 'slash') is now our regexp delimiter... */
  266. if (*cmdstr == '\0')
  267. bb_error_msg_and_die("bad format in substitution expression");
  268. delimiter = *cmdstr_ptr++;
  269. /* save the match string */
  270. idx = index_of_next_unescaped_regexp_delim(delimiter, cmdstr_ptr);
  271. *match = copy_parsing_escapes(cmdstr_ptr, idx);
  272. /* save the replacement string */
  273. cmdstr_ptr += idx + 1;
  274. idx = index_of_next_unescaped_regexp_delim(- (int)delimiter, cmdstr_ptr);
  275. *replace = copy_parsing_escapes(cmdstr_ptr, idx);
  276. return ((cmdstr_ptr - cmdstr) + idx);
  277. }
  278. /*
  279. * returns the index in the string just past where the address ends.
  280. */
  281. static int get_address(const char *my_str, int *linenum, regex_t ** regex)
  282. {
  283. const char *pos = my_str;
  284. if (isdigit(*my_str)) {
  285. *linenum = strtol(my_str, (char**)&pos, 10);
  286. /* endstr shouldn't ever equal NULL */
  287. } else if (*my_str == '$') {
  288. *linenum = -1;
  289. pos++;
  290. } else if (*my_str == '/' || *my_str == '\\') {
  291. int next;
  292. char delimiter;
  293. char *temp;
  294. delimiter = '/';
  295. if (*my_str == '\\')
  296. delimiter = *++pos;
  297. next = index_of_next_unescaped_regexp_delim(delimiter, ++pos);
  298. if (next != 0) {
  299. temp = copy_parsing_escapes(pos, next);
  300. G.previous_regex_ptr = *regex = xzalloc(sizeof(regex_t));
  301. xregcomp(*regex, temp, G.regex_type);
  302. free(temp);
  303. } else {
  304. *regex = G.previous_regex_ptr;
  305. if (!G.previous_regex_ptr)
  306. bb_error_msg_and_die("no previous regexp");
  307. }
  308. /* Move position to next character after last delimiter */
  309. pos += (next+1);
  310. }
  311. return pos - my_str;
  312. }
  313. /* Grab a filename. Whitespace at start is skipped, then goes to EOL. */
  314. static int parse_file_cmd(/*sed_cmd_t *sed_cmd,*/ const char *filecmdstr, char **retval)
  315. {
  316. int start = 0, idx, hack = 0;
  317. /* Skip whitespace, then grab filename to end of line */
  318. while (isspace(filecmdstr[start]))
  319. start++;
  320. idx = start;
  321. while (filecmdstr[idx] && filecmdstr[idx] != '\n')
  322. idx++;
  323. /* If lines glued together, put backslash back. */
  324. if (filecmdstr[idx] == '\n')
  325. hack = 1;
  326. if (idx == start)
  327. bb_error_msg_and_die("empty filename");
  328. *retval = xstrndup(filecmdstr+start, idx-start+hack+1);
  329. if (hack)
  330. (*retval)[idx] = '\\';
  331. return idx;
  332. }
  333. static int parse_subst_cmd(sed_cmd_t *sed_cmd, const char *substr)
  334. {
  335. int cflags = G.regex_type;
  336. char *match;
  337. int idx;
  338. /*
  339. * A substitution command should look something like this:
  340. * s/match/replace/ #giIpw
  341. * || | |||
  342. * mandatory optional
  343. */
  344. idx = parse_regex_delim(substr, &match, &sed_cmd->string);
  345. /* determine the number of back references in the match string */
  346. /* Note: we compute this here rather than in the do_subst_command()
  347. * function to save processor time, at the expense of a little more memory
  348. * (4 bits) per sed_cmd */
  349. /* process the flags */
  350. sed_cmd->which_match = 1;
  351. dbg("s flags:'%s'", substr + idx + 1);
  352. while (substr[++idx]) {
  353. dbg("s flag:'%c'", substr[idx]);
  354. /* Parse match number */
  355. if (isdigit(substr[idx])) {
  356. if (match[0] != '^') {
  357. /* Match 0 treated as all, multiple matches we take the last one. */
  358. const char *pos = substr + idx;
  359. /* FIXME: error check? */
  360. sed_cmd->which_match = (unsigned)strtol(substr+idx, (char**) &pos, 10);
  361. idx = pos - substr - 1;
  362. }
  363. continue;
  364. }
  365. /* Skip spaces */
  366. if (isspace(substr[idx]))
  367. continue;
  368. switch (substr[idx]) {
  369. /* Replace all occurrences */
  370. case 'g':
  371. if (match[0] != '^')
  372. sed_cmd->which_match = 0;
  373. break;
  374. /* Print pattern space */
  375. case 'p':
  376. sed_cmd->sub_p = 1;
  377. break;
  378. /* Write to file */
  379. case 'w':
  380. {
  381. char *fname;
  382. idx += parse_file_cmd(/*sed_cmd,*/ substr+idx+1, &fname);
  383. sed_cmd->sw_file = xfopen_for_write(fname);
  384. sed_cmd->sw_last_char = '\n';
  385. free(fname);
  386. break;
  387. }
  388. /* Ignore case (gnu extension) */
  389. case 'i':
  390. case 'I':
  391. cflags |= REG_ICASE;
  392. break;
  393. /* Comment */
  394. case '#':
  395. // while (substr[++idx]) continue;
  396. idx += strlen(substr + idx); // same
  397. /* Fall through */
  398. /* End of command */
  399. case ';':
  400. case '}':
  401. goto out;
  402. default:
  403. dbg("s bad flags:'%s'", substr + idx);
  404. bb_error_msg_and_die("bad option in substitution expression");
  405. }
  406. }
  407. out:
  408. /* compile the match string into a regex */
  409. if (*match != '\0') {
  410. /* If match is empty, we use last regex used at runtime */
  411. sed_cmd->sub_match = xzalloc(sizeof(regex_t));
  412. dbg("xregcomp('%s',%x)", match, cflags);
  413. xregcomp(sed_cmd->sub_match, match, cflags);
  414. dbg("regcomp ok");
  415. }
  416. free(match);
  417. return idx;
  418. }
  419. /*
  420. * Process the commands arguments
  421. */
  422. static const char *parse_cmd_args(sed_cmd_t *sed_cmd, const char *cmdstr)
  423. {
  424. static const char cmd_letters[] ALIGN1 = "saicrw:btTydDgGhHlnNpPqx={}";
  425. enum {
  426. IDX_s = 0,
  427. IDX_a,
  428. IDX_i,
  429. IDX_c,
  430. IDX_r,
  431. IDX_w,
  432. IDX_colon,
  433. IDX_b,
  434. IDX_t,
  435. IDX_T,
  436. IDX_y,
  437. IDX_d,
  438. IDX_D,
  439. IDX_g,
  440. IDX_G,
  441. IDX_h,
  442. IDX_H,
  443. IDX_l,
  444. IDX_n,
  445. IDX_N,
  446. IDX_p,
  447. IDX_P,
  448. IDX_q,
  449. IDX_x,
  450. IDX_equal,
  451. IDX_lbrace,
  452. IDX_rbrace,
  453. IDX_nul
  454. };
  455. unsigned idx;
  456. BUILD_BUG_ON(sizeof(cmd_letters)-1 != IDX_nul);
  457. idx = strchrnul(cmd_letters, sed_cmd->cmd) - cmd_letters;
  458. /* handle (s)ubstitution command */
  459. if (idx == IDX_s) {
  460. cmdstr += parse_subst_cmd(sed_cmd, cmdstr);
  461. }
  462. /* handle edit cmds: (a)ppend, (i)nsert, and (c)hange */
  463. else if (idx <= IDX_c) { /* a,i,c */
  464. unsigned len;
  465. if (idx < IDX_c) { /* a,i */
  466. if (sed_cmd->end_line || sed_cmd->end_match)
  467. bb_error_msg_and_die("command '%c' uses only one address", sed_cmd->cmd);
  468. }
  469. for (;;) {
  470. if (*cmdstr == '\n' || *cmdstr == '\\') {
  471. cmdstr++;
  472. break;
  473. }
  474. if (!isspace(*cmdstr))
  475. break;
  476. cmdstr++;
  477. }
  478. len = strlen(cmdstr);
  479. sed_cmd->string = copy_parsing_escapes(cmdstr, len);
  480. cmdstr += len;
  481. /* "\anychar" -> "anychar" */
  482. parse_escapes(sed_cmd->string, sed_cmd->string, -1, '\0', '\0');
  483. }
  484. /* handle file cmds: (r)ead */
  485. else if (idx <= IDX_w) { /* r,w */
  486. if (idx < IDX_w) { /* r */
  487. if (sed_cmd->end_line || sed_cmd->end_match)
  488. bb_error_msg_and_die("command '%c' uses only one address", sed_cmd->cmd);
  489. }
  490. cmdstr += parse_file_cmd(/*sed_cmd,*/ cmdstr, &sed_cmd->string);
  491. if (sed_cmd->cmd == 'w') {
  492. sed_cmd->sw_file = xfopen_for_write(sed_cmd->string);
  493. sed_cmd->sw_last_char = '\n';
  494. }
  495. }
  496. /* handle branch commands */
  497. else if (idx <= IDX_T) { /* :,b,t,T */
  498. int length;
  499. cmdstr = skip_whitespace(cmdstr);
  500. length = strcspn(cmdstr, semicolon_whitespace);
  501. if (length) {
  502. sed_cmd->string = xstrndup(cmdstr, length);
  503. cmdstr += length;
  504. }
  505. }
  506. /* translation command */
  507. else if (idx == IDX_y) {
  508. char *match, *replace;
  509. int i = cmdstr[0];
  510. cmdstr += parse_regex_delim(cmdstr, &match, &replace)+1;
  511. /* \n already parsed, but \delimiter needs unescaping. */
  512. parse_escapes(match, match, -1, i, i);
  513. parse_escapes(replace, replace, -1, i, i);
  514. sed_cmd->string = xzalloc((strlen(match) + 1) * 2);
  515. for (i = 0; match[i] && replace[i]; i++) {
  516. sed_cmd->string[i*2] = match[i];
  517. sed_cmd->string[i*2+1] = replace[i];
  518. }
  519. free(match);
  520. free(replace);
  521. }
  522. /* if it wasn't a single-letter command that takes no arguments
  523. * then it must be an invalid command.
  524. */
  525. else if (idx >= IDX_nul) { /* not d,D,g,G,h,H,l,n,N,p,P,q,x,=,{,} */
  526. bb_error_msg_and_die("unsupported command %c", sed_cmd->cmd);
  527. }
  528. /* give back whatever's left over */
  529. return cmdstr;
  530. }
  531. /* Parse address+command sets, skipping comment lines. */
  532. static void add_cmd(const char *cmdstr)
  533. {
  534. sed_cmd_t *sed_cmd;
  535. unsigned len, n;
  536. /* Append this line to any unfinished line from last time. */
  537. if (G.add_cmd_line) {
  538. char *tp = xasprintf("%s\n%s", G.add_cmd_line, cmdstr);
  539. free(G.add_cmd_line);
  540. cmdstr = G.add_cmd_line = tp;
  541. }
  542. /* If this line ends with unescaped backslash, request next line. */
  543. n = len = strlen(cmdstr);
  544. while (n && cmdstr[n-1] == '\\')
  545. n--;
  546. if ((len - n) & 1) { /* if odd number of trailing backslashes */
  547. if (!G.add_cmd_line)
  548. G.add_cmd_line = xstrdup(cmdstr);
  549. G.add_cmd_line[len-1] = '\0';
  550. return;
  551. }
  552. /* Loop parsing all commands in this line. */
  553. while (*cmdstr) {
  554. /* Skip leading whitespace and semicolons */
  555. cmdstr += strspn(cmdstr, semicolon_whitespace);
  556. /* If no more commands, exit. */
  557. if (!*cmdstr) break;
  558. /* if this is a comment, jump past it and keep going */
  559. if (*cmdstr == '#') {
  560. /* "#n" is the same as using -n on the command line */
  561. if (cmdstr[1] == 'n')
  562. G.be_quiet++;
  563. cmdstr = strpbrk(cmdstr, "\n\r");
  564. if (!cmdstr) break;
  565. continue;
  566. }
  567. /* parse the command
  568. * format is: [addr][,addr][!]cmd
  569. * |----||-----||-|
  570. * part1 part2 part3
  571. */
  572. sed_cmd = xzalloc(sizeof(sed_cmd_t));
  573. /* first part (if present) is an address: either a '$', a number or a /regex/ */
  574. cmdstr += get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
  575. sed_cmd->beg_line_orig = sed_cmd->beg_line;
  576. /* second part (if present) will begin with a comma */
  577. if (*cmdstr == ',') {
  578. int idx;
  579. cmdstr++;
  580. if (*cmdstr == '+' && isdigit(cmdstr[1])) {
  581. /* http://sed.sourceforge.net/sedfaq3.html#s3.3
  582. * Under GNU sed 3.02+, ssed, and sed15+, <address2>
  583. * may also be a notation of the form +num,
  584. * indicating the next num lines after <address1> is
  585. * matched.
  586. * GNU sed 4.2.1 accepts even "+" (meaning "+0").
  587. * We don't (we check for isdigit, see above), think
  588. * about the "+-3" case.
  589. */
  590. char *end;
  591. /* code is smaller compared to using &cmdstr here: */
  592. idx = strtol(cmdstr+1, &end, 10);
  593. sed_cmd->end_line = -2 - idx;
  594. cmdstr = end;
  595. } else {
  596. idx = get_address(cmdstr, &sed_cmd->end_line, &sed_cmd->end_match);
  597. cmdstr += idx;
  598. idx--; /* if 0, trigger error check below */
  599. }
  600. if (idx < 0)
  601. bb_error_msg_and_die("no address after comma");
  602. sed_cmd->end_line_orig = sed_cmd->end_line;
  603. }
  604. /* skip whitespace before the command */
  605. cmdstr = skip_whitespace(cmdstr);
  606. /* Check for inversion flag */
  607. if (*cmdstr == '!') {
  608. sed_cmd->invert = 1;
  609. cmdstr++;
  610. /* skip whitespace before the command */
  611. cmdstr = skip_whitespace(cmdstr);
  612. }
  613. /* last part (mandatory) will be a command */
  614. if (!*cmdstr)
  615. bb_error_msg_and_die("missing command");
  616. sed_cmd->cmd = *cmdstr++;
  617. cmdstr = parse_cmd_args(sed_cmd, cmdstr);
  618. /* cmdstr now points past args.
  619. * GNU sed requires a separator, if there are more commands,
  620. * else it complains "char N: extra characters after command".
  621. * Example: "sed 'p;d'". We also allow "sed 'pd'".
  622. */
  623. /* Add the command to the command array */
  624. *G.sed_cmd_tail = sed_cmd;
  625. G.sed_cmd_tail = &sed_cmd->next;
  626. }
  627. /* If we glued multiple lines together, free the memory. */
  628. free(G.add_cmd_line);
  629. G.add_cmd_line = NULL;
  630. }
  631. /* Append to a string, reallocating memory as necessary. */
  632. #define PIPE_GROW 64
  633. static void pipe_putc(char c)
  634. {
  635. if (G.pipeline.idx == G.pipeline.len) {
  636. G.pipeline.buf = xrealloc(G.pipeline.buf,
  637. G.pipeline.len + PIPE_GROW);
  638. G.pipeline.len += PIPE_GROW;
  639. }
  640. G.pipeline.buf[G.pipeline.idx++] = c;
  641. }
  642. static void do_subst_w_backrefs(char *line, char *replace)
  643. {
  644. int i, j;
  645. /* go through the replacement string */
  646. for (i = 0; replace[i]; i++) {
  647. /* if we find a backreference (\1, \2, etc.) print the backref'ed text */
  648. if (replace[i] == '\\') {
  649. unsigned backref = replace[++i] - '0';
  650. if (backref <= 9) {
  651. /* print out the text held in G.regmatch[backref] */
  652. if (G.regmatch[backref].rm_so != -1) {
  653. j = G.regmatch[backref].rm_so;
  654. while (j < G.regmatch[backref].rm_eo)
  655. pipe_putc(line[j++]);
  656. }
  657. continue;
  658. }
  659. /* I _think_ it is impossible to get '\' to be
  660. * the last char in replace string. Thus we don't check
  661. * for replace[i] == NUL. (counterexample anyone?) */
  662. /* if we find a backslash escaped character, print the character */
  663. pipe_putc(replace[i]);
  664. continue;
  665. }
  666. /* if we find an unescaped '&' print out the whole matched text. */
  667. if (replace[i] == '&') {
  668. j = G.regmatch[0].rm_so;
  669. while (j < G.regmatch[0].rm_eo)
  670. pipe_putc(line[j++]);
  671. continue;
  672. }
  673. /* Otherwise just output the character. */
  674. pipe_putc(replace[i]);
  675. }
  676. }
  677. static int do_subst_command(sed_cmd_t *sed_cmd, char **line_p)
  678. {
  679. char *line = *line_p;
  680. unsigned match_count = 0;
  681. bool altered = 0;
  682. bool prev_match_empty = 1;
  683. bool tried_at_eol = 0;
  684. regex_t *current_regex;
  685. current_regex = sed_cmd->sub_match;
  686. /* Handle empty regex. */
  687. if (!current_regex) {
  688. current_regex = G.previous_regex_ptr;
  689. if (!current_regex)
  690. bb_error_msg_and_die("no previous regexp");
  691. }
  692. G.previous_regex_ptr = current_regex;
  693. /* Find the first match */
  694. dbg("matching '%s'", line);
  695. if (REG_NOMATCH == regexec(current_regex, line, 10, G.regmatch, 0)) {
  696. dbg("no match");
  697. return 0;
  698. }
  699. dbg("match");
  700. /* Initialize temporary output buffer. */
  701. G.pipeline.buf = xmalloc(PIPE_GROW);
  702. G.pipeline.len = PIPE_GROW;
  703. G.pipeline.idx = 0;
  704. /* Now loop through, substituting for matches */
  705. do {
  706. int start = G.regmatch[0].rm_so;
  707. int end = G.regmatch[0].rm_eo;
  708. int i;
  709. match_count++;
  710. /* If we aren't interested in this match, output old line to
  711. * end of match and continue */
  712. if (sed_cmd->which_match
  713. && (sed_cmd->which_match != match_count)
  714. ) {
  715. for (i = 0; i < end; i++)
  716. pipe_putc(*line++);
  717. /* Null match? Print one more char */
  718. if (start == end && *line)
  719. pipe_putc(*line++);
  720. goto next;
  721. }
  722. /* Print everything before the match */
  723. for (i = 0; i < start; i++)
  724. pipe_putc(line[i]);
  725. /* Then print the substitution string,
  726. * unless we just matched empty string after non-empty one.
  727. * Example: string "cccd", pattern "c*", repl "R":
  728. * result is "RdR", not "RRdR": first match "ccc",
  729. * second is "" before "d", third is "" after "d".
  730. * Second match is NOT replaced!
  731. */
  732. if (prev_match_empty || start != 0 || start != end) {
  733. //dbg("%d %d %d", prev_match_empty, start, end);
  734. dbg("inserting replacement at %d in '%s'", start, line);
  735. do_subst_w_backrefs(line, sed_cmd->string);
  736. /* Flag that something has changed */
  737. altered = 1;
  738. } else {
  739. dbg("NOT inserting replacement at %d in '%s'", start, line);
  740. }
  741. /* If matched string is empty (f.e. "c*" pattern),
  742. * copy verbatim one char after it before attempting more matches
  743. */
  744. prev_match_empty = (start == end);
  745. if (prev_match_empty) {
  746. if (!line[end]) {
  747. tried_at_eol = 1;
  748. } else {
  749. pipe_putc(line[end]);
  750. end++;
  751. }
  752. }
  753. /* Advance past the match */
  754. dbg("line += %d", end);
  755. line += end;
  756. /* if we're not doing this globally, get out now */
  757. if (sed_cmd->which_match != 0)
  758. break;
  759. next:
  760. /* Exit if we are at EOL and already tried matching at it */
  761. if (*line == '\0') {
  762. if (tried_at_eol)
  763. break;
  764. tried_at_eol = 1;
  765. }
  766. //maybe (end ? REG_NOTBOL : 0) instead of unconditional REG_NOTBOL?
  767. } while (regexec(current_regex, line, 10, G.regmatch, REG_NOTBOL) != REG_NOMATCH);
  768. /* Copy rest of string into output pipeline */
  769. while (1) {
  770. char c = *line++;
  771. pipe_putc(c);
  772. if (c == '\0')
  773. break;
  774. }
  775. free(*line_p);
  776. *line_p = G.pipeline.buf;
  777. return altered;
  778. }
  779. /* Set command pointer to point to this label. (Does not handle null label.) */
  780. static sed_cmd_t *branch_to(char *label)
  781. {
  782. sed_cmd_t *sed_cmd;
  783. for (sed_cmd = G.sed_cmd_head; sed_cmd; sed_cmd = sed_cmd->next) {
  784. if (sed_cmd->cmd == ':'
  785. && sed_cmd->string
  786. && strcmp(sed_cmd->string, label) == 0
  787. ) {
  788. return sed_cmd;
  789. }
  790. }
  791. bb_error_msg_and_die("can't find label for jump to '%s'", label);
  792. }
  793. static void append(char *s)
  794. {
  795. llist_add_to_end(&G.append_head, s);
  796. }
  797. /* Output line of text. */
  798. /* Note:
  799. * The tricks with NO_EOL_CHAR and last_puts_char are there to emulate gnu sed.
  800. * Without them, we had this:
  801. * echo -n thingy >z1
  802. * echo -n again >z2
  803. * >znull
  804. * sed "s/i/z/" z1 z2 znull | hexdump -vC
  805. * output:
  806. * gnu sed 4.1.5:
  807. * 00000000 74 68 7a 6e 67 79 0a 61 67 61 7a 6e |thzngy.agazn|
  808. * bbox:
  809. * 00000000 74 68 7a 6e 67 79 61 67 61 7a 6e |thzngyagazn|
  810. */
  811. enum {
  812. NO_EOL_CHAR = 1,
  813. LAST_IS_NUL = 2,
  814. };
  815. static void puts_maybe_newline(char *s, FILE *file, char *last_puts_char, char last_gets_char)
  816. {
  817. char lpc = *last_puts_char;
  818. /* Need to insert a '\n' between two files because first file's
  819. * last line wasn't terminated? */
  820. if (lpc != '\n' && lpc != '\0') {
  821. fputc('\n', file);
  822. lpc = '\n';
  823. }
  824. fputs(s, file);
  825. /* 'x' - just something which is not '\n', '\0' or NO_EOL_CHAR */
  826. if (s[0])
  827. lpc = 'x';
  828. /* had trailing '\0' and it was last char of file? */
  829. if (last_gets_char == LAST_IS_NUL) {
  830. fputc('\0', file);
  831. lpc = 'x'; /* */
  832. } else
  833. /* had trailing '\n' or '\0'? */
  834. if (last_gets_char != NO_EOL_CHAR) {
  835. fputc(last_gets_char, file);
  836. lpc = last_gets_char;
  837. }
  838. if (ferror(file)) {
  839. xfunc_error_retval = 4; /* It's what gnu sed exits with... */
  840. bb_error_msg_and_die(bb_msg_write_error);
  841. }
  842. *last_puts_char = lpc;
  843. }
  844. static void flush_append(char *last_puts_char)
  845. {
  846. char *data;
  847. /* Output appended lines. */
  848. while ((data = (char *)llist_pop(&G.append_head)) != NULL) {
  849. /* Append command does not respect "nonterminated-ness"
  850. * of last line. Try this:
  851. * $ echo -n "woot" | sed -e '/woot/a woo' -
  852. * woot
  853. * woo
  854. * (both lines are terminated with \n)
  855. * Therefore we do not propagate "last_gets_char" here,
  856. * pass '\n' instead:
  857. */
  858. puts_maybe_newline(data, G.nonstdout, last_puts_char, '\n');
  859. free(data);
  860. }
  861. }
  862. /* Get next line of input from G.input_file_list, flushing append buffer and
  863. * noting if we ran out of files without a newline on the last line we read.
  864. */
  865. static char *get_next_line(char *gets_char, char *last_puts_char)
  866. {
  867. char *temp = NULL;
  868. size_t len;
  869. char gc;
  870. flush_append(last_puts_char);
  871. /* will be returned if last line in the file
  872. * doesn't end with either '\n' or '\0' */
  873. gc = NO_EOL_CHAR;
  874. for (; G.current_input_file <= G.last_input_file; G.current_input_file++) {
  875. FILE *fp = G.current_fp;
  876. if (!fp) {
  877. const char *path = G.input_file_list[G.current_input_file];
  878. fp = stdin;
  879. if (path != bb_msg_standard_input) {
  880. fp = fopen_or_warn(path, "r");
  881. if (!fp) {
  882. G.exitcode = EXIT_FAILURE;
  883. continue;
  884. }
  885. }
  886. G.current_fp = fp;
  887. }
  888. /* Read line up to a newline or NUL byte, inclusive,
  889. * return malloc'ed char[]. length of the chunk read
  890. * is stored in len. NULL if EOF/error */
  891. temp = bb_get_chunk_from_file(fp, &len);
  892. if (temp) {
  893. /* len > 0 here, it's ok to do temp[len-1] */
  894. char c = temp[len-1];
  895. if (c == '\n' || c == '\0') {
  896. temp[len-1] = '\0';
  897. gc = c;
  898. if (c == '\0') {
  899. int ch = fgetc(fp);
  900. if (ch != EOF)
  901. ungetc(ch, fp);
  902. else
  903. gc = LAST_IS_NUL;
  904. }
  905. }
  906. /* else we put NO_EOL_CHAR into *gets_char */
  907. break;
  908. /* NB: I had the idea of peeking next file(s) and returning
  909. * NO_EOL_CHAR only if it is the *last* non-empty
  910. * input file. But there is a case where this won't work:
  911. * file1: "a woo\nb woo"
  912. * file2: "c no\nd no"
  913. * sed -ne 's/woo/bang/p' input1 input2 => "a bang\nb bang"
  914. * (note: *no* newline after "b bang"!) */
  915. }
  916. /* Close this file and advance to next one */
  917. fclose_if_not_stdin(fp);
  918. G.current_fp = NULL;
  919. }
  920. *gets_char = gc;
  921. return temp;
  922. }
  923. #define sed_puts(s, n) (puts_maybe_newline(s, G.nonstdout, &last_puts_char, n))
  924. static int beg_match(sed_cmd_t *sed_cmd, const char *pattern_space)
  925. {
  926. int retval = sed_cmd->beg_match && !regexec(sed_cmd->beg_match, pattern_space, 0, NULL, 0);
  927. if (retval)
  928. G.previous_regex_ptr = sed_cmd->beg_match;
  929. return retval;
  930. }
  931. /* Process all the lines in all the files */
  932. static void process_files(void)
  933. {
  934. char *pattern_space, *next_line;
  935. int linenum = 0;
  936. char last_puts_char = '\n';
  937. char last_gets_char, next_gets_char;
  938. sed_cmd_t *sed_cmd;
  939. int substituted;
  940. /* Prime the pump */
  941. next_line = get_next_line(&next_gets_char, &last_puts_char);
  942. /* Go through every line in each file */
  943. again:
  944. substituted = 0;
  945. /* Advance to next line. Stop if out of lines. */
  946. pattern_space = next_line;
  947. if (!pattern_space)
  948. return;
  949. last_gets_char = next_gets_char;
  950. /* Read one line in advance so we can act on the last line,
  951. * the '$' address */
  952. next_line = get_next_line(&next_gets_char, &last_puts_char);
  953. linenum++;
  954. /* For every line, go through all the commands */
  955. restart:
  956. for (sed_cmd = G.sed_cmd_head; sed_cmd; sed_cmd = sed_cmd->next) {
  957. int old_matched, matched;
  958. old_matched = sed_cmd->in_match;
  959. /* Determine if this command matches this line: */
  960. dbg("match1:%d", sed_cmd->in_match);
  961. dbg("match2:%d", (!sed_cmd->beg_line && !sed_cmd->end_line
  962. && !sed_cmd->beg_match && !sed_cmd->end_match));
  963. dbg("match3:%d", (sed_cmd->beg_line > 0
  964. && (sed_cmd->end_line || sed_cmd->end_match
  965. ? (sed_cmd->beg_line <= linenum)
  966. : (sed_cmd->beg_line == linenum)
  967. )
  968. ));
  969. dbg("match4:%d", (beg_match(sed_cmd, pattern_space)));
  970. dbg("match5:%d", (sed_cmd->beg_line == -1 && next_line == NULL));
  971. /* Are we continuing a previous multi-line match? */
  972. sed_cmd->in_match = sed_cmd->in_match
  973. /* Or is no range necessary? */
  974. || (!sed_cmd->beg_line && !sed_cmd->end_line
  975. && !sed_cmd->beg_match && !sed_cmd->end_match)
  976. /* Or did we match the start of a numerical range? */
  977. || (sed_cmd->beg_line > 0
  978. && (sed_cmd->end_line || sed_cmd->end_match
  979. /* note: even if end is numeric and is < linenum too,
  980. * GNU sed matches! We match too, therefore we don't
  981. * check here that linenum <= end.
  982. * Example:
  983. * printf '1\n2\n3\n4\n' | sed -n '1{N;N;d};1p;2,3p;3p;4p'
  984. * first three input lines are deleted;
  985. * 4th line is matched and printed
  986. * by "2,3" (!) and by "4" ranges
  987. */
  988. ? (sed_cmd->beg_line <= linenum) /* N,end */
  989. : (sed_cmd->beg_line == linenum) /* N */
  990. )
  991. )
  992. /* Or does this line match our begin address regex? */
  993. || (beg_match(sed_cmd, pattern_space))
  994. /* Or did we match last line of input? */
  995. || (sed_cmd->beg_line == -1 && next_line == NULL);
  996. /* Snapshot the value */
  997. matched = sed_cmd->in_match;
  998. dbg("cmd:'%c' matched:%d beg_line:%d end_line:%d linenum:%d",
  999. sed_cmd->cmd, matched, sed_cmd->beg_line, sed_cmd->end_line, linenum);
  1000. /* Is this line the end of the current match? */
  1001. if (matched) {
  1002. if (sed_cmd->end_line <= -2) {
  1003. /* address2 is +N, i.e. N lines from beg_line */
  1004. sed_cmd->end_line = linenum + (-sed_cmd->end_line - 2);
  1005. }
  1006. /* once matched, "n,xxx" range is dead, disabling it */
  1007. if (sed_cmd->beg_line > 0) {
  1008. sed_cmd->beg_line = -2;
  1009. }
  1010. dbg("end1:%d", sed_cmd->end_line ? sed_cmd->end_line == -1
  1011. ? !next_line : (sed_cmd->end_line <= linenum)
  1012. : !sed_cmd->end_match);
  1013. dbg("end2:%d", sed_cmd->end_match && old_matched
  1014. && !regexec(sed_cmd->end_match,pattern_space, 0, NULL, 0));
  1015. sed_cmd->in_match = !(
  1016. /* has the ending line come, or is this a single address command? */
  1017. (sed_cmd->end_line
  1018. ? sed_cmd->end_line == -1
  1019. ? !next_line
  1020. : (sed_cmd->end_line <= linenum)
  1021. : !sed_cmd->end_match
  1022. )
  1023. /* or does this line matches our last address regex */
  1024. || (sed_cmd->end_match && old_matched
  1025. && (regexec(sed_cmd->end_match,
  1026. pattern_space, 0, NULL, 0) == 0)
  1027. )
  1028. );
  1029. }
  1030. /* Skip blocks of commands we didn't match */
  1031. if (sed_cmd->cmd == '{') {
  1032. if (sed_cmd->invert ? matched : !matched) {
  1033. unsigned nest_cnt = 0;
  1034. while (1) {
  1035. if (sed_cmd->cmd == '{')
  1036. nest_cnt++;
  1037. if (sed_cmd->cmd == '}') {
  1038. nest_cnt--;
  1039. if (nest_cnt == 0)
  1040. break;
  1041. }
  1042. sed_cmd = sed_cmd->next;
  1043. if (!sed_cmd)
  1044. bb_error_msg_and_die("unterminated {");
  1045. }
  1046. }
  1047. continue;
  1048. }
  1049. /* Okay, so did this line match? */
  1050. if (sed_cmd->invert ? matched : !matched)
  1051. continue; /* no */
  1052. /* Update last used regex in case a blank substitute BRE is found */
  1053. if (sed_cmd->beg_match) {
  1054. G.previous_regex_ptr = sed_cmd->beg_match;
  1055. }
  1056. /* actual sedding */
  1057. dbg("pattern_space:'%s' next_line:'%s' cmd:%c",
  1058. pattern_space, next_line, sed_cmd->cmd);
  1059. switch (sed_cmd->cmd) {
  1060. /* Print line number */
  1061. case '=':
  1062. fprintf(G.nonstdout, "%d\n", linenum);
  1063. break;
  1064. /* Write the current pattern space up to the first newline */
  1065. case 'P':
  1066. {
  1067. char *tmp = strchr(pattern_space, '\n');
  1068. if (tmp) {
  1069. *tmp = '\0';
  1070. /* TODO: explain why '\n' below */
  1071. sed_puts(pattern_space, '\n');
  1072. *tmp = '\n';
  1073. break;
  1074. }
  1075. /* Fall Through */
  1076. }
  1077. /* Write the current pattern space to output */
  1078. case 'p':
  1079. /* NB: we print this _before_ the last line
  1080. * (of current file) is printed. Even if
  1081. * that line is nonterminated, we print
  1082. * '\n' here (gnu sed does the same) */
  1083. sed_puts(pattern_space, '\n');
  1084. break;
  1085. /* Delete up through first newline */
  1086. case 'D':
  1087. {
  1088. char *tmp = strchr(pattern_space, '\n');
  1089. if (tmp) {
  1090. overlapping_strcpy(pattern_space, tmp + 1);
  1091. goto restart;
  1092. }
  1093. }
  1094. /* discard this line. */
  1095. case 'd':
  1096. goto discard_line;
  1097. /* Substitute with regex */
  1098. case 's':
  1099. if (!do_subst_command(sed_cmd, &pattern_space))
  1100. break;
  1101. dbg("do_subst_command succeeded:'%s'", pattern_space);
  1102. substituted |= 1;
  1103. /* handle p option */
  1104. if (sed_cmd->sub_p)
  1105. sed_puts(pattern_space, last_gets_char);
  1106. /* handle w option */
  1107. if (sed_cmd->sw_file)
  1108. puts_maybe_newline(
  1109. pattern_space, sed_cmd->sw_file,
  1110. &sed_cmd->sw_last_char, last_gets_char);
  1111. break;
  1112. /* Append line to linked list to be printed later */
  1113. case 'a':
  1114. append(xstrdup(sed_cmd->string));
  1115. break;
  1116. /* Insert text before this line */
  1117. case 'i':
  1118. sed_puts(sed_cmd->string, '\n');
  1119. break;
  1120. /* Cut and paste text (replace) */
  1121. case 'c':
  1122. /* Only triggers on last line of a matching range. */
  1123. if (!sed_cmd->in_match)
  1124. sed_puts(sed_cmd->string, '\n');
  1125. goto discard_line;
  1126. /* Read file, append contents to output */
  1127. case 'r':
  1128. {
  1129. FILE *rfile;
  1130. rfile = fopen_for_read(sed_cmd->string);
  1131. if (rfile) {
  1132. char *line;
  1133. while ((line = xmalloc_fgetline(rfile))
  1134. != NULL)
  1135. append(line);
  1136. fclose(rfile);
  1137. }
  1138. break;
  1139. }
  1140. /* Write pattern space to file. */
  1141. case 'w':
  1142. puts_maybe_newline(
  1143. pattern_space, sed_cmd->sw_file,
  1144. &sed_cmd->sw_last_char, last_gets_char);
  1145. break;
  1146. /* Read next line from input */
  1147. case 'n':
  1148. if (!G.be_quiet)
  1149. sed_puts(pattern_space, last_gets_char);
  1150. if (next_line == NULL) {
  1151. /* If no next line, jump to end of script and exit. */
  1152. goto discard_line;
  1153. }
  1154. free(pattern_space);
  1155. pattern_space = next_line;
  1156. last_gets_char = next_gets_char;
  1157. next_line = get_next_line(&next_gets_char, &last_puts_char);
  1158. substituted = 0;
  1159. linenum++;
  1160. break;
  1161. /* Quit. End of script, end of input. */
  1162. case 'q':
  1163. /* Exit the outer while loop */
  1164. free(next_line);
  1165. next_line = NULL;
  1166. goto discard_commands;
  1167. /* Append the next line to the current line */
  1168. case 'N':
  1169. {
  1170. int len;
  1171. /* If no next line, jump to end of script and exit. */
  1172. /* http://www.gnu.org/software/sed/manual/sed.html:
  1173. * "Most versions of sed exit without printing anything
  1174. * when the N command is issued on the last line of
  1175. * a file. GNU sed prints pattern space before exiting
  1176. * unless of course the -n command switch has been
  1177. * specified. This choice is by design."
  1178. */
  1179. if (next_line == NULL) {
  1180. //goto discard_line;
  1181. goto discard_commands; /* GNU behavior */
  1182. }
  1183. /* Append next_line, read new next_line. */
  1184. len = strlen(pattern_space);
  1185. pattern_space = xrealloc(pattern_space, len + strlen(next_line) + 2);
  1186. pattern_space[len] = '\n';
  1187. strcpy(pattern_space + len+1, next_line);
  1188. last_gets_char = next_gets_char;
  1189. next_line = get_next_line(&next_gets_char, &last_puts_char);
  1190. linenum++;
  1191. break;
  1192. }
  1193. /* Test/branch if substitution occurred */
  1194. case 't':
  1195. if (!substituted) break;
  1196. substituted = 0;
  1197. /* Fall through */
  1198. /* Test/branch if substitution didn't occur */
  1199. case 'T':
  1200. if (substituted) break;
  1201. /* Fall through */
  1202. /* Branch to label */
  1203. case 'b':
  1204. if (!sed_cmd->string) goto discard_commands;
  1205. else sed_cmd = branch_to(sed_cmd->string);
  1206. break;
  1207. /* Transliterate characters */
  1208. case 'y':
  1209. {
  1210. int i, j;
  1211. for (i = 0; pattern_space[i]; i++) {
  1212. for (j = 0; sed_cmd->string[j]; j += 2) {
  1213. if (pattern_space[i] == sed_cmd->string[j]) {
  1214. pattern_space[i] = sed_cmd->string[j + 1];
  1215. break;
  1216. }
  1217. }
  1218. }
  1219. break;
  1220. }
  1221. case 'g': /* Replace pattern space with hold space */
  1222. free(pattern_space);
  1223. pattern_space = xstrdup(G.hold_space ? G.hold_space : "");
  1224. break;
  1225. case 'G': /* Append newline and hold space to pattern space */
  1226. {
  1227. int pattern_space_size = 2;
  1228. int hold_space_size = 0;
  1229. if (pattern_space)
  1230. pattern_space_size += strlen(pattern_space);
  1231. if (G.hold_space)
  1232. hold_space_size = strlen(G.hold_space);
  1233. pattern_space = xrealloc(pattern_space,
  1234. pattern_space_size + hold_space_size);
  1235. if (pattern_space_size == 2)
  1236. pattern_space[0] = 0;
  1237. strcat(pattern_space, "\n");
  1238. if (G.hold_space)
  1239. strcat(pattern_space, G.hold_space);
  1240. last_gets_char = '\n';
  1241. break;
  1242. }
  1243. case 'h': /* Replace hold space with pattern space */
  1244. free(G.hold_space);
  1245. G.hold_space = xstrdup(pattern_space);
  1246. break;
  1247. case 'H': /* Append newline and pattern space to hold space */
  1248. {
  1249. int hold_space_size = 2;
  1250. int pattern_space_size = 0;
  1251. if (G.hold_space)
  1252. hold_space_size += strlen(G.hold_space);
  1253. if (pattern_space)
  1254. pattern_space_size = strlen(pattern_space);
  1255. G.hold_space = xrealloc(G.hold_space,
  1256. hold_space_size + pattern_space_size);
  1257. if (hold_space_size == 2)
  1258. *G.hold_space = 0;
  1259. strcat(G.hold_space, "\n");
  1260. if (pattern_space)
  1261. strcat(G.hold_space, pattern_space);
  1262. break;
  1263. }
  1264. case 'x': /* Exchange hold and pattern space */
  1265. {
  1266. char *tmp = pattern_space;
  1267. pattern_space = G.hold_space ? G.hold_space : xzalloc(1);
  1268. last_gets_char = '\n';
  1269. G.hold_space = tmp;
  1270. break;
  1271. }
  1272. } /* switch */
  1273. } /* for each cmd */
  1274. /*
  1275. * Exit point from sedding...
  1276. */
  1277. discard_commands:
  1278. /* we will print the line unless we were told to be quiet ('-n')
  1279. or if the line was suppressed (ala 'd'elete) */
  1280. if (!G.be_quiet)
  1281. sed_puts(pattern_space, last_gets_char);
  1282. /* Delete and such jump here. */
  1283. discard_line:
  1284. flush_append(&last_puts_char /*,last_gets_char*/);
  1285. free(pattern_space);
  1286. goto again;
  1287. }
  1288. /* It is possible to have a command line argument with embedded
  1289. * newlines. This counts as multiple command lines.
  1290. * However, newline can be escaped: 's/e/z\<newline>z/'
  1291. * add_cmd() handles this.
  1292. */
  1293. static void add_cmd_block(char *cmdstr)
  1294. {
  1295. char *sv, *eol;
  1296. cmdstr = sv = xstrdup(cmdstr);
  1297. do {
  1298. eol = strchr(cmdstr, '\n');
  1299. if (eol)
  1300. *eol = '\0';
  1301. add_cmd(cmdstr);
  1302. cmdstr = eol + 1;
  1303. } while (eol);
  1304. free(sv);
  1305. }
  1306. int sed_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1307. int sed_main(int argc UNUSED_PARAM, char **argv)
  1308. {
  1309. unsigned opt;
  1310. llist_t *opt_e, *opt_f;
  1311. char *opt_i;
  1312. #if ENABLE_LONG_OPTS
  1313. static const char sed_longopts[] ALIGN1 =
  1314. /* name has_arg short */
  1315. "in-place\0" Optional_argument "i"
  1316. "regexp-extended\0" No_argument "r"
  1317. "quiet\0" No_argument "n"
  1318. "silent\0" No_argument "n"
  1319. "expression\0" Required_argument "e"
  1320. "file\0" Required_argument "f";
  1321. #endif
  1322. INIT_G();
  1323. /* destroy command strings on exit */
  1324. if (ENABLE_FEATURE_CLEAN_UP) atexit(sed_free_and_close_stuff);
  1325. /* Lie to autoconf when it starts asking stupid questions. */
  1326. if (argv[1] && strcmp(argv[1], "--version") == 0) {
  1327. puts("This is not GNU sed version 4.0");
  1328. return 0;
  1329. }
  1330. /* do normal option parsing */
  1331. opt_e = opt_f = NULL;
  1332. opt_i = NULL;
  1333. /* -i must be first, to match OPT_in_place definition */
  1334. /* -E is a synonym of -r:
  1335. * GNU sed 4.2.1 mentions it in neither --help
  1336. * nor manpage, but does recognize it.
  1337. */
  1338. opt = getopt32long(argv, "^"
  1339. "i::rEne:*f:*"
  1340. "\0" "nn"/*count -n*/,
  1341. sed_longopts,
  1342. &opt_i, &opt_e, &opt_f,
  1343. &G.be_quiet); /* counter for -n */
  1344. //argc -= optind;
  1345. argv += optind;
  1346. if (opt & OPT_in_place) { // -i
  1347. die_func = cleanup_outname;
  1348. }
  1349. if (opt & (2|4))
  1350. G.regex_type |= REG_EXTENDED; // -r or -E
  1351. //if (opt & 8)
  1352. // G.be_quiet++; // -n (implemented with a counter instead)
  1353. while (opt_e) { // -e
  1354. add_cmd_block(llist_pop(&opt_e));
  1355. }
  1356. while (opt_f) { // -f
  1357. char *line;
  1358. FILE *cmdfile;
  1359. cmdfile = xfopen_stdin(llist_pop(&opt_f));
  1360. while ((line = xmalloc_fgetline(cmdfile)) != NULL) {
  1361. add_cmd(line);
  1362. free(line);
  1363. }
  1364. fclose_if_not_stdin(cmdfile);
  1365. }
  1366. /* if we didn't get a pattern from -e or -f, use argv[0] */
  1367. if (!(opt & 0x30)) {
  1368. if (!*argv)
  1369. bb_show_usage();
  1370. add_cmd_block(*argv++);
  1371. }
  1372. /* Flush any unfinished commands. */
  1373. add_cmd("");
  1374. /* By default, we write to stdout */
  1375. G.nonstdout = stdout;
  1376. /* argv[0..(argc-1)] should be names of file to process. If no
  1377. * files were specified or '-' was specified, take input from stdin.
  1378. * Otherwise, we process all the files specified. */
  1379. G.input_file_list = argv;
  1380. if (!argv[0]) {
  1381. if (opt & OPT_in_place)
  1382. bb_error_msg_and_die(bb_msg_requires_arg, "-i");
  1383. argv[0] = (char*)bb_msg_standard_input;
  1384. /* G.last_input_file = 0; - already is */
  1385. } else {
  1386. goto start;
  1387. for (; *argv; argv++) {
  1388. struct stat statbuf;
  1389. int nonstdoutfd;
  1390. sed_cmd_t *sed_cmd;
  1391. G.last_input_file++;
  1392. start:
  1393. if (!(opt & OPT_in_place)) {
  1394. if (LONE_DASH(*argv)) {
  1395. *argv = (char*)bb_msg_standard_input;
  1396. process_files();
  1397. }
  1398. continue;
  1399. }
  1400. /* -i: process each FILE separately: */
  1401. if (stat(*argv, &statbuf) != 0) {
  1402. bb_simple_perror_msg(*argv);
  1403. G.exitcode = EXIT_FAILURE;
  1404. G.current_input_file++;
  1405. continue;
  1406. }
  1407. G.outname = xasprintf("%sXXXXXX", *argv);
  1408. nonstdoutfd = xmkstemp(G.outname);
  1409. G.nonstdout = xfdopen_for_write(nonstdoutfd);
  1410. /* Set permissions/owner of output file */
  1411. /* chmod'ing AFTER chown would preserve suid/sgid bits,
  1412. * but GNU sed 4.2.1 does not preserve them either */
  1413. fchmod(nonstdoutfd, statbuf.st_mode);
  1414. fchown(nonstdoutfd, statbuf.st_uid, statbuf.st_gid);
  1415. process_files();
  1416. fclose(G.nonstdout);
  1417. G.nonstdout = stdout;
  1418. if (opt_i) {
  1419. char *backupname = xasprintf("%s%s", *argv, opt_i);
  1420. xrename(*argv, backupname);
  1421. free(backupname);
  1422. }
  1423. /* else unlink(*argv); - rename below does this */
  1424. xrename(G.outname, *argv); //TODO: rollback backup on error?
  1425. free(G.outname);
  1426. G.outname = NULL;
  1427. /* Fix disabled range matches and mangled ",+N" ranges */
  1428. for (sed_cmd = G.sed_cmd_head; sed_cmd; sed_cmd = sed_cmd->next) {
  1429. sed_cmd->beg_line = sed_cmd->beg_line_orig;
  1430. sed_cmd->end_line = sed_cmd->end_line_orig;
  1431. }
  1432. }
  1433. /* Here, to handle "sed 'cmds' nonexistent_file" case we did:
  1434. * if (G.current_input_file[G.current_input_file] == NULL)
  1435. * return G.exitcode;
  1436. * but it's not needed since process_files() works correctly
  1437. * in this case too. */
  1438. }
  1439. process_files();
  1440. return G.exitcode;
  1441. }