tr.c 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. //usage:#define tr_trivial_usage
  48. //usage: "[-cds] STRING1 [STRING2]"
  49. //usage:#define tr_full_usage "\n\n"
  50. //usage: "Translate, squeeze, or delete characters from stdin, writing to stdout\n"
  51. //usage: "\n -c Take complement of STRING1"
  52. //usage: "\n -d Delete input characters coded STRING1"
  53. //usage: "\n -s Squeeze multiple output characters of STRING2 into one character"
  54. //usage:
  55. //usage:#define tr_example_usage
  56. //usage: "$ echo \"gdkkn vnqkc\" | tr [a-y] [b-z]\n"
  57. //usage: "hello world\n"
  58. #include "libbb.h"
  59. enum {
  60. ASCII = 256,
  61. /* string buffer needs to be at least as big as the whole "alphabet".
  62. * BUFSIZ == ASCII is ok, but we will realloc in expand
  63. * even for smallest patterns, let's avoid that by using *2:
  64. */
  65. TR_BUFSIZ = (BUFSIZ > ASCII*2) ? BUFSIZ : ASCII*2,
  66. };
  67. static void map(char *pvector,
  68. char *string1, unsigned string1_len,
  69. char *string2, unsigned string2_len)
  70. {
  71. char last = '0';
  72. unsigned i, j;
  73. for (j = 0, i = 0; i < string1_len; i++) {
  74. if (string2_len <= j)
  75. pvector[(unsigned char)(string1[i])] = last;
  76. else
  77. pvector[(unsigned char)(string1[i])] = last = string2[j++];
  78. }
  79. }
  80. /* supported constructs:
  81. * Ranges, e.g., 0-9 ==> 0123456789
  82. * Escapes, e.g., \a ==> Control-G
  83. * Character classes, e.g. [:upper:] ==> A...Z
  84. * Equiv classess, e.g. [=A=] ==> A (hmmmmmmm?)
  85. * not supported:
  86. * \ooo-\ooo - octal ranges
  87. * [x*N] - repeat char x N times
  88. * [x*] - repeat char x until it fills STRING2:
  89. * # echo qwe123 | /usr/bin/tr 123456789 '[d]'
  90. * qwe[d]
  91. * # echo qwe123 | /usr/bin/tr 123456789 '[d*]'
  92. * qweddd
  93. */
  94. static unsigned expand(const char *arg, char **buffer_p)
  95. {
  96. char *buffer = *buffer_p;
  97. unsigned pos = 0;
  98. unsigned size = TR_BUFSIZ;
  99. unsigned i; /* can't be unsigned char: must be able to hold 256 */
  100. unsigned char ac;
  101. while (*arg) {
  102. if (pos + ASCII > size) {
  103. size += ASCII;
  104. *buffer_p = buffer = xrealloc(buffer, size);
  105. }
  106. if (*arg == '\\') {
  107. arg++;
  108. buffer[pos++] = bb_process_escape_sequence(&arg);
  109. continue;
  110. }
  111. if (arg[1] == '-') { /* "0-9..." */
  112. ac = arg[2];
  113. if (ac == '\0') { /* "0-": copy verbatim */
  114. buffer[pos++] = *arg++; /* copy '0' */
  115. continue; /* next iter will copy '-' and stop */
  116. }
  117. i = (unsigned char) *arg;
  118. while (i <= ac) /* ok: i is unsigned _int_ */
  119. buffer[pos++] = i++;
  120. arg += 3; /* skip 0-9 */
  121. continue;
  122. }
  123. if ((ENABLE_FEATURE_TR_CLASSES || ENABLE_FEATURE_TR_EQUIV)
  124. && *arg == '['
  125. ) {
  126. arg++;
  127. i = (unsigned char) *arg++;
  128. /* "[xyz...". i=x, arg points to y */
  129. if (ENABLE_FEATURE_TR_CLASSES && i == ':') { /* [:class:] */
  130. #define CLO ":]\0"
  131. static const char classes[] ALIGN1 =
  132. "alpha"CLO "alnum"CLO "digit"CLO
  133. "lower"CLO "upper"CLO "space"CLO
  134. "blank"CLO "punct"CLO "cntrl"CLO
  135. "xdigit"CLO;
  136. enum {
  137. CLASS_invalid = 0, /* we increment the retval */
  138. CLASS_alpha = 1,
  139. CLASS_alnum = 2,
  140. CLASS_digit = 3,
  141. CLASS_lower = 4,
  142. CLASS_upper = 5,
  143. CLASS_space = 6,
  144. CLASS_blank = 7,
  145. CLASS_punct = 8,
  146. CLASS_cntrl = 9,
  147. CLASS_xdigit = 10,
  148. //CLASS_graph = 11,
  149. //CLASS_print = 12,
  150. };
  151. smalluint j;
  152. char *tmp;
  153. /* xdigit needs 8, not 7 */
  154. i = 7 + (arg[0] == 'x');
  155. tmp = xstrndup(arg, i);
  156. j = index_in_strings(classes, tmp) + 1;
  157. free(tmp);
  158. if (j == CLASS_invalid)
  159. goto skip_bracket;
  160. arg += i;
  161. if (j == CLASS_alnum || j == CLASS_digit || j == CLASS_xdigit) {
  162. for (i = '0'; i <= '9'; i++)
  163. buffer[pos++] = i;
  164. }
  165. if (j == CLASS_alpha || j == CLASS_alnum || j == CLASS_upper) {
  166. for (i = 'A'; i <= 'Z'; i++)
  167. buffer[pos++] = i;
  168. }
  169. if (j == CLASS_alpha || j == CLASS_alnum || j == CLASS_lower) {
  170. for (i = 'a'; i <= 'z'; i++)
  171. buffer[pos++] = i;
  172. }
  173. if (j == CLASS_space || j == CLASS_blank) {
  174. buffer[pos++] = '\t';
  175. if (j == CLASS_space) {
  176. buffer[pos++] = '\n';
  177. buffer[pos++] = '\v';
  178. buffer[pos++] = '\f';
  179. buffer[pos++] = '\r';
  180. }
  181. buffer[pos++] = ' ';
  182. }
  183. if (j == CLASS_punct || j == CLASS_cntrl) {
  184. for (i = '\0'; i < ASCII; i++) {
  185. if ((j == CLASS_punct && isprint_asciionly(i) && !isalnum(i) && !isspace(i))
  186. || (j == CLASS_cntrl && iscntrl(i))
  187. ) {
  188. buffer[pos++] = i;
  189. }
  190. }
  191. }
  192. if (j == CLASS_xdigit) {
  193. for (i = 'A'; i <= 'F'; i++) {
  194. buffer[pos + 6] = i | 0x20;
  195. buffer[pos++] = i;
  196. }
  197. pos += 6;
  198. }
  199. continue;
  200. }
  201. /* "[xyz...", i=x, arg points to y */
  202. if (ENABLE_FEATURE_TR_EQUIV && i == '=') { /* [=CHAR=] */
  203. buffer[pos++] = *arg; /* copy CHAR */
  204. if (!arg[0] || arg[1] != '=' || arg[2] != ']')
  205. bb_show_usage();
  206. arg += 3; /* skip CHAR=] */
  207. continue;
  208. }
  209. /* The rest of "[xyz..." cases is treated as normal
  210. * string, "[" has no special meaning here:
  211. * tr "[a-z]" "[A-Z]" can be written as tr "a-z" "A-Z",
  212. * also try tr "[a-z]" "_A-Z+" and you'll see that
  213. * [] is not special here.
  214. */
  215. skip_bracket:
  216. arg -= 2; /* points to "[" in "[xyz..." */
  217. }
  218. buffer[pos++] = *arg++;
  219. }
  220. return pos;
  221. }
  222. /* NB: buffer is guaranteed to be at least TR_BUFSIZE
  223. * (which is >= ASCII) big.
  224. */
  225. static int complement(char *buffer, int buffer_len)
  226. {
  227. int len;
  228. char conv[ASCII];
  229. unsigned char ch;
  230. len = 0;
  231. ch = '\0';
  232. while (1) {
  233. if (memchr(buffer, ch, buffer_len) == NULL)
  234. conv[len++] = ch;
  235. if (++ch == '\0')
  236. break;
  237. }
  238. memcpy(buffer, conv, len);
  239. return len;
  240. }
  241. int tr_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  242. int tr_main(int argc UNUSED_PARAM, char **argv)
  243. {
  244. int i;
  245. smalluint opts;
  246. ssize_t read_chars;
  247. size_t in_index, out_index;
  248. unsigned last = UCHAR_MAX + 1; /* not equal to any char */
  249. unsigned char coded, c;
  250. char *str1 = xmalloc(TR_BUFSIZ);
  251. char *str2 = xmalloc(TR_BUFSIZ);
  252. int str2_length;
  253. int str1_length;
  254. char *vector = xzalloc(ASCII * 3);
  255. char *invec = vector + ASCII;
  256. char *outvec = vector + ASCII * 2;
  257. #define TR_OPT_complement (3 << 0)
  258. #define TR_OPT_delete (1 << 2)
  259. #define TR_OPT_squeeze_reps (1 << 3)
  260. for (i = 0; i < ASCII; i++) {
  261. vector[i] = i;
  262. /*invec[i] = outvec[i] = FALSE; - done by xzalloc */
  263. }
  264. /* -C/-c difference is that -C complements "characters",
  265. * and -c complements "values" (binary bytes I guess).
  266. * In POSIX locale, these are the same.
  267. */
  268. opt_complementary = "-1";
  269. opts = getopt32(argv, "+Ccds"); /* '+': stop at first non-option */
  270. argv += optind;
  271. str1_length = expand(*argv++, &str1);
  272. str2_length = 0;
  273. if (opts & TR_OPT_complement)
  274. str1_length = complement(str1, str1_length);
  275. if (*argv) {
  276. if (argv[0][0] == '\0')
  277. bb_error_msg_and_die("STRING2 cannot be empty");
  278. str2_length = expand(*argv, &str2);
  279. map(vector, str1, str1_length,
  280. str2, str2_length);
  281. }
  282. for (i = 0; i < str1_length; i++)
  283. invec[(unsigned char)(str1[i])] = TRUE;
  284. for (i = 0; i < str2_length; i++)
  285. outvec[(unsigned char)(str2[i])] = TRUE;
  286. goto start_from;
  287. /* In this loop, str1 space is reused as input buffer,
  288. * str2 - as output one. */
  289. for (;;) {
  290. /* If we're out of input, flush output and read more input. */
  291. if ((ssize_t)in_index == read_chars) {
  292. if (out_index) {
  293. xwrite(STDOUT_FILENO, str2, out_index);
  294. start_from:
  295. out_index = 0;
  296. }
  297. read_chars = safe_read(STDIN_FILENO, str1, TR_BUFSIZ);
  298. if (read_chars <= 0) {
  299. if (read_chars < 0)
  300. bb_perror_msg_and_die(bb_msg_read_error);
  301. break;
  302. }
  303. in_index = 0;
  304. }
  305. c = str1[in_index++];
  306. if ((opts & TR_OPT_delete) && invec[c])
  307. continue;
  308. coded = vector[c];
  309. if ((opts & TR_OPT_squeeze_reps) && last == coded
  310. && (invec[c] || outvec[coded])
  311. ) {
  312. continue;
  313. }
  314. str2[out_index++] = last = coded;
  315. }
  316. if (ENABLE_FEATURE_CLEAN_UP) {
  317. free(vector);
  318. free(str2);
  319. free(str1);
  320. }
  321. return EXIT_SUCCESS;
  322. }