3
0

tr.c 9.5 KB

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