tr.c 9.5 KB

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