tr.c 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini tr implementation for busybox
  4. *
  5. ** Copyright (c) 1987,1997, Prentice Hall All rights reserved.
  6. *
  7. * The name of Prentice Hall may not be used to endorse or promote
  8. * products derived from this software without specific prior
  9. * written permission.
  10. *
  11. * Copyright (c) Michiel Huisjes
  12. *
  13. * This version of tr is adapted from Minix tr and was modified
  14. * by Erik Andersen <andersen@codepoet.org> to be used in busybox.
  15. *
  16. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  17. */
  18. /* http://www.opengroup.org/onlinepubs/009695399/utilities/tr.html
  19. * TODO: graph, print
  20. */
  21. //kbuild:lib-$(CONFIG_TR) += tr.o
  22. //config:config TR
  23. //config: bool "tr"
  24. //config: default y
  25. //config: help
  26. //config: tr is used to squeeze, and/or delete characters from standard
  27. //config: input, writing to standard output.
  28. //config:
  29. //config:config FEATURE_TR_CLASSES
  30. //config: bool "Enable character classes (such as [:upper:])"
  31. //config: default y
  32. //config: depends on TR
  33. //config: help
  34. //config: Enable character classes, enabling commands such as:
  35. //config: tr [:upper:] [:lower:] to convert input into lowercase.
  36. //config:
  37. //config:config FEATURE_TR_EQUIV
  38. //config: bool "Enable equivalence classes"
  39. //config: default y
  40. //config: depends on TR
  41. //config: help
  42. //config: Enable equivalence classes, which essentially add the enclosed
  43. //config: character to the current set. For instance, tr [=a=] xyz would
  44. //config: replace all instances of 'a' with 'xyz'. This option is mainly
  45. //config: useful for cases when no other way of expressing a character
  46. //config: is possible.
  47. #include "libbb.h"
  48. enum {
  49. ASCII = 256,
  50. /* string buffer needs to be at least as big as the whole "alphabet".
  51. * BUFSIZ == ASCII is ok, but we will realloc in expand
  52. * even for smallest patterns, let's avoid that by using *2:
  53. */
  54. TR_BUFSIZ = (BUFSIZ > ASCII*2) ? BUFSIZ : ASCII*2,
  55. };
  56. static void map(char *pvector,
  57. char *string1, unsigned string1_len,
  58. char *string2, unsigned string2_len)
  59. {
  60. char last = '0';
  61. unsigned i, j;
  62. for (j = 0, i = 0; i < string1_len; i++) {
  63. if (string2_len <= j)
  64. pvector[(unsigned char)(string1[i])] = last;
  65. else
  66. pvector[(unsigned char)(string1[i])] = last = string2[j++];
  67. }
  68. }
  69. /* supported constructs:
  70. * Ranges, e.g., 0-9 ==> 0123456789
  71. * Escapes, e.g., \a ==> Control-G
  72. * Character classes, e.g. [:upper:] ==> A...Z
  73. * Equiv classess, e.g. [=A=] ==> A (hmmmmmmm?)
  74. * not supported:
  75. * \ooo-\ooo - octal ranges
  76. * [x*N] - repeat char x N times
  77. * [x*] - repeat char x until it fills STRING2:
  78. * # echo qwe123 | /usr/bin/tr 123456789 '[d]'
  79. * qwe[d]
  80. * # echo qwe123 | /usr/bin/tr 123456789 '[d*]'
  81. * qweddd
  82. */
  83. static unsigned expand(const char *arg, char **buffer_p)
  84. {
  85. char *buffer = *buffer_p;
  86. unsigned pos = 0;
  87. unsigned size = TR_BUFSIZ;
  88. unsigned i; /* can't be unsigned char: must be able to hold 256 */
  89. unsigned char ac;
  90. while (*arg) {
  91. if (pos + ASCII > size) {
  92. size += ASCII;
  93. *buffer_p = buffer = xrealloc(buffer, size);
  94. }
  95. if (*arg == '\\') {
  96. arg++;
  97. buffer[pos++] = bb_process_escape_sequence(&arg);
  98. continue;
  99. }
  100. if (arg[1] == '-') { /* "0-9..." */
  101. ac = arg[2];
  102. if (ac == '\0') { /* "0-": copy verbatim */
  103. buffer[pos++] = *arg++; /* copy '0' */
  104. continue; /* next iter will copy '-' and stop */
  105. }
  106. i = (unsigned char) *arg;
  107. while (i <= ac) /* ok: i is unsigned _int_ */
  108. buffer[pos++] = i++;
  109. arg += 3; /* skip 0-9 */
  110. continue;
  111. }
  112. if ((ENABLE_FEATURE_TR_CLASSES || ENABLE_FEATURE_TR_EQUIV)
  113. && *arg == '['
  114. ) {
  115. arg++;
  116. i = (unsigned char) *arg++;
  117. /* "[xyz...". i=x, arg points to y */
  118. if (ENABLE_FEATURE_TR_CLASSES && i == ':') { /* [:class:] */
  119. #define CLO ":]\0"
  120. static const char classes[] ALIGN1 =
  121. "alpha"CLO "alnum"CLO "digit"CLO
  122. "lower"CLO "upper"CLO "space"CLO
  123. "blank"CLO "punct"CLO "cntrl"CLO
  124. "xdigit"CLO;
  125. enum {
  126. CLASS_invalid = 0, /* we increment the retval */
  127. CLASS_alpha = 1,
  128. CLASS_alnum = 2,
  129. CLASS_digit = 3,
  130. CLASS_lower = 4,
  131. CLASS_upper = 5,
  132. CLASS_space = 6,
  133. CLASS_blank = 7,
  134. CLASS_punct = 8,
  135. CLASS_cntrl = 9,
  136. CLASS_xdigit = 10,
  137. //CLASS_graph = 11,
  138. //CLASS_print = 12,
  139. };
  140. smalluint j;
  141. char *tmp;
  142. /* xdigit needs 8, not 7 */
  143. i = 7 + (arg[0] == 'x');
  144. tmp = xstrndup(arg, i);
  145. j = index_in_strings(classes, tmp) + 1;
  146. free(tmp);
  147. if (j == CLASS_invalid)
  148. goto skip_bracket;
  149. arg += i;
  150. if (j == CLASS_alnum || j == CLASS_digit || j == CLASS_xdigit) {
  151. for (i = '0'; i <= '9'; i++)
  152. buffer[pos++] = i;
  153. }
  154. if (j == CLASS_alpha || j == CLASS_alnum || j == CLASS_upper) {
  155. for (i = 'A'; i <= 'Z'; i++)
  156. buffer[pos++] = i;
  157. }
  158. if (j == CLASS_alpha || j == CLASS_alnum || j == CLASS_lower) {
  159. for (i = 'a'; i <= 'z'; i++)
  160. buffer[pos++] = i;
  161. }
  162. if (j == CLASS_space || j == CLASS_blank) {
  163. buffer[pos++] = '\t';
  164. if (j == CLASS_space) {
  165. buffer[pos++] = '\n';
  166. buffer[pos++] = '\v';
  167. buffer[pos++] = '\f';
  168. buffer[pos++] = '\r';
  169. }
  170. buffer[pos++] = ' ';
  171. }
  172. if (j == CLASS_punct || j == CLASS_cntrl) {
  173. for (i = '\0'; i < ASCII; i++) {
  174. if ((j == CLASS_punct && isprint_asciionly(i) && !isalnum(i) && !isspace(i))
  175. || (j == CLASS_cntrl && iscntrl(i))
  176. ) {
  177. buffer[pos++] = i;
  178. }
  179. }
  180. }
  181. if (j == CLASS_xdigit) {
  182. for (i = 'A'; i <= 'F'; i++) {
  183. buffer[pos + 6] = i | 0x20;
  184. buffer[pos++] = i;
  185. }
  186. pos += 6;
  187. }
  188. continue;
  189. }
  190. /* "[xyz...", i=x, arg points to y */
  191. if (ENABLE_FEATURE_TR_EQUIV && i == '=') { /* [=CHAR=] */
  192. buffer[pos++] = *arg; /* copy CHAR */
  193. if (!arg[0] || arg[1] != '=' || arg[2] != ']')
  194. bb_show_usage();
  195. arg += 3; /* skip CHAR=] */
  196. continue;
  197. }
  198. /* The rest of "[xyz..." cases is treated as normal
  199. * string, "[" has no special meaning here:
  200. * tr "[a-z]" "[A-Z]" can be written as tr "a-z" "A-Z",
  201. * also try tr "[a-z]" "_A-Z+" and you'll see that
  202. * [] is not special here.
  203. */
  204. skip_bracket:
  205. arg -= 2; /* points to "[" in "[xyz..." */
  206. }
  207. buffer[pos++] = *arg++;
  208. }
  209. return pos;
  210. }
  211. /* NB: buffer is guaranteed to be at least TR_BUFSIZE
  212. * (which is >= ASCII) big.
  213. */
  214. static int complement(char *buffer, int buffer_len)
  215. {
  216. int len;
  217. char conv[ASCII];
  218. unsigned char ch;
  219. len = 0;
  220. ch = '\0';
  221. while (1) {
  222. if (memchr(buffer, ch, buffer_len) == NULL)
  223. conv[len++] = ch;
  224. if (++ch == '\0')
  225. break;
  226. }
  227. memcpy(buffer, conv, len);
  228. return len;
  229. }
  230. int tr_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  231. int tr_main(int argc UNUSED_PARAM, char **argv)
  232. {
  233. int i;
  234. smalluint opts;
  235. ssize_t read_chars;
  236. size_t in_index, out_index;
  237. unsigned last = UCHAR_MAX + 1; /* not equal to any char */
  238. unsigned char coded, c;
  239. char *str1 = xmalloc(TR_BUFSIZ);
  240. char *str2 = xmalloc(TR_BUFSIZ);
  241. int str2_length;
  242. int str1_length;
  243. char *vector = xzalloc(ASCII * 3);
  244. char *invec = vector + ASCII;
  245. char *outvec = vector + ASCII * 2;
  246. #define TR_OPT_complement (3 << 0)
  247. #define TR_OPT_delete (1 << 2)
  248. #define TR_OPT_squeeze_reps (1 << 3)
  249. for (i = 0; i < ASCII; i++) {
  250. vector[i] = i;
  251. /*invec[i] = outvec[i] = FALSE; - done by xzalloc */
  252. }
  253. /* -C/-c difference is that -C complements "characters",
  254. * and -c complements "values" (binary bytes I guess).
  255. * In POSIX locale, these are the same.
  256. */
  257. opt_complementary = "-1";
  258. opts = getopt32(argv, "+Ccds"); /* '+': stop at first non-option */
  259. argv += optind;
  260. str1_length = expand(*argv++, &str1);
  261. str2_length = 0;
  262. if (opts & TR_OPT_complement)
  263. str1_length = complement(str1, str1_length);
  264. if (*argv) {
  265. if (argv[0][0] == '\0')
  266. bb_error_msg_and_die("STRING2 cannot be empty");
  267. str2_length = expand(*argv, &str2);
  268. map(vector, str1, str1_length,
  269. str2, str2_length);
  270. }
  271. for (i = 0; i < str1_length; i++)
  272. invec[(unsigned char)(str1[i])] = TRUE;
  273. for (i = 0; i < str2_length; i++)
  274. outvec[(unsigned char)(str2[i])] = TRUE;
  275. goto start_from;
  276. /* In this loop, str1 space is reused as input buffer,
  277. * str2 - as output one. */
  278. for (;;) {
  279. /* If we're out of input, flush output and read more input. */
  280. if ((ssize_t)in_index == read_chars) {
  281. if (out_index) {
  282. xwrite(STDOUT_FILENO, str2, out_index);
  283. start_from:
  284. out_index = 0;
  285. }
  286. read_chars = safe_read(STDIN_FILENO, str1, TR_BUFSIZ);
  287. if (read_chars <= 0) {
  288. if (read_chars < 0)
  289. bb_perror_msg_and_die(bb_msg_read_error);
  290. break;
  291. }
  292. in_index = 0;
  293. }
  294. c = str1[in_index++];
  295. if ((opts & TR_OPT_delete) && invec[c])
  296. continue;
  297. coded = vector[c];
  298. if ((opts & TR_OPT_squeeze_reps) && last == coded
  299. && (invec[c] || outvec[coded])
  300. ) {
  301. continue;
  302. }
  303. str2[out_index++] = last = coded;
  304. }
  305. return EXIT_SUCCESS;
  306. }