cut.c 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * cut.c - minimalist version of cut
  4. *
  5. * Copyright (C) 1999,2000,2001 by Lineo, inc.
  6. * Written by Mark Whitley <markw@codepoet.org>
  7. * debloated by Bernhard Reutner-Fischer
  8. *
  9. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  10. */
  11. //usage:#define cut_trivial_usage
  12. //usage: "[OPTIONS] [FILE]..."
  13. //usage:#define cut_full_usage "\n\n"
  14. //usage: "Print selected fields from each input FILE to stdout\n"
  15. //usage: "\n -b LIST Output only bytes from LIST"
  16. //usage: "\n -c LIST Output only characters from LIST"
  17. //usage: "\n -d CHAR Use CHAR instead of tab as the field delimiter"
  18. //usage: "\n -s Output only the lines containing delimiter"
  19. //usage: "\n -f N Print only these fields"
  20. //usage: "\n -n Ignored"
  21. //usage:
  22. //usage:#define cut_example_usage
  23. //usage: "$ echo \"Hello world\" | cut -f 1 -d ' '\n"
  24. //usage: "Hello\n"
  25. //usage: "$ echo \"Hello world\" | cut -f 2 -d ' '\n"
  26. //usage: "world\n"
  27. #include "libbb.h"
  28. /* This is a NOEXEC applet. Be very careful! */
  29. /* option vars */
  30. static const char optstring[] ALIGN1 = "b:c:f:d:sn";
  31. #define CUT_OPT_BYTE_FLGS (1 << 0)
  32. #define CUT_OPT_CHAR_FLGS (1 << 1)
  33. #define CUT_OPT_FIELDS_FLGS (1 << 2)
  34. #define CUT_OPT_DELIM_FLGS (1 << 3)
  35. #define CUT_OPT_SUPPRESS_FLGS (1 << 4)
  36. struct cut_list {
  37. int startpos;
  38. int endpos;
  39. };
  40. enum {
  41. BOL = 0,
  42. EOL = INT_MAX,
  43. NON_RANGE = -1
  44. };
  45. static int cmpfunc(const void *a, const void *b)
  46. {
  47. return (((struct cut_list *) a)->startpos -
  48. ((struct cut_list *) b)->startpos);
  49. }
  50. static void cut_file(FILE *file, char delim, const struct cut_list *cut_lists, unsigned nlists)
  51. {
  52. char *line;
  53. unsigned linenum = 0; /* keep these zero-based to be consistent */
  54. /* go through every line in the file */
  55. while ((line = xmalloc_fgetline(file)) != NULL) {
  56. /* set up a list so we can keep track of what's been printed */
  57. int linelen = strlen(line);
  58. char *printed = xzalloc(linelen + 1);
  59. char *orig_line = line;
  60. unsigned cl_pos = 0;
  61. int spos;
  62. /* cut based on chars/bytes XXX: only works when sizeof(char) == byte */
  63. if (option_mask32 & (CUT_OPT_CHAR_FLGS | CUT_OPT_BYTE_FLGS)) {
  64. /* print the chars specified in each cut list */
  65. for (; cl_pos < nlists; cl_pos++) {
  66. spos = cut_lists[cl_pos].startpos;
  67. while (spos < linelen) {
  68. if (!printed[spos]) {
  69. printed[spos] = 'X';
  70. putchar(line[spos]);
  71. }
  72. spos++;
  73. if (spos > cut_lists[cl_pos].endpos
  74. /* NON_RANGE is -1, so if below is true,
  75. * the above was true too (spos is >= 0) */
  76. /* || cut_lists[cl_pos].endpos == NON_RANGE */
  77. ) {
  78. break;
  79. }
  80. }
  81. }
  82. } else if (delim == '\n') { /* cut by lines */
  83. spos = cut_lists[cl_pos].startpos;
  84. /* get out if we have no more lists to process or if the lines
  85. * are lower than what we're interested in */
  86. if (((int)linenum < spos) || (cl_pos >= nlists))
  87. goto next_line;
  88. /* if the line we're looking for is lower than the one we were
  89. * passed, it means we displayed it already, so move on */
  90. while (spos < (int)linenum) {
  91. spos++;
  92. /* go to the next list if we're at the end of this one */
  93. if (spos > cut_lists[cl_pos].endpos
  94. || cut_lists[cl_pos].endpos == NON_RANGE
  95. ) {
  96. cl_pos++;
  97. /* get out if there's no more lists to process */
  98. if (cl_pos >= nlists)
  99. goto next_line;
  100. spos = cut_lists[cl_pos].startpos;
  101. /* get out if the current line is lower than the one
  102. * we just became interested in */
  103. if ((int)linenum < spos)
  104. goto next_line;
  105. }
  106. }
  107. /* If we made it here, it means we've found the line we're
  108. * looking for, so print it */
  109. puts(line);
  110. goto next_line;
  111. } else { /* cut by fields */
  112. int ndelim = -1; /* zero-based / one-based problem */
  113. int nfields_printed = 0;
  114. char *field = NULL;
  115. char delimiter[2];
  116. delimiter[0] = delim;
  117. delimiter[1] = 0;
  118. /* does this line contain any delimiters? */
  119. if (strchr(line, delim) == NULL) {
  120. if (!(option_mask32 & CUT_OPT_SUPPRESS_FLGS))
  121. puts(line);
  122. goto next_line;
  123. }
  124. /* process each list on this line, for as long as we've got
  125. * a line to process */
  126. for (; cl_pos < nlists && line; cl_pos++) {
  127. spos = cut_lists[cl_pos].startpos;
  128. do {
  129. /* find the field we're looking for */
  130. while (line && ndelim < spos) {
  131. field = strsep(&line, delimiter);
  132. ndelim++;
  133. }
  134. /* we found it, and it hasn't been printed yet */
  135. if (field && ndelim == spos && !printed[ndelim]) {
  136. /* if this isn't our first time through, we need to
  137. * print the delimiter after the last field that was
  138. * printed */
  139. if (nfields_printed > 0)
  140. putchar(delim);
  141. fputs(field, stdout);
  142. printed[ndelim] = 'X';
  143. nfields_printed++; /* shouldn't overflow.. */
  144. }
  145. spos++;
  146. /* keep going as long as we have a line to work with,
  147. * this is a list, and we're not at the end of that
  148. * list */
  149. } while (spos <= cut_lists[cl_pos].endpos && line
  150. && cut_lists[cl_pos].endpos != NON_RANGE);
  151. }
  152. }
  153. /* if we printed anything at all, we need to finish it with a
  154. * newline cuz we were handed a chomped line */
  155. putchar('\n');
  156. next_line:
  157. linenum++;
  158. free(printed);
  159. free(orig_line);
  160. }
  161. }
  162. int cut_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  163. int cut_main(int argc UNUSED_PARAM, char **argv)
  164. {
  165. /* growable array holding a series of lists */
  166. struct cut_list *cut_lists = NULL;
  167. unsigned nlists = 0; /* number of elements in above list */
  168. char delim = '\t'; /* delimiter, default is tab */
  169. char *sopt, *ltok;
  170. unsigned opt;
  171. opt_complementary = "b--bcf:c--bcf:f--bcf";
  172. opt = getopt32(argv, optstring, &sopt, &sopt, &sopt, &ltok);
  173. // argc -= optind;
  174. argv += optind;
  175. if (!(opt & (CUT_OPT_BYTE_FLGS | CUT_OPT_CHAR_FLGS | CUT_OPT_FIELDS_FLGS)))
  176. bb_error_msg_and_die("expected a list of bytes, characters, or fields");
  177. if (opt & CUT_OPT_DELIM_FLGS) {
  178. if (ltok[0] && ltok[1]) { /* more than 1 char? */
  179. bb_error_msg_and_die("the delimiter must be a single character");
  180. }
  181. delim = ltok[0];
  182. }
  183. /* non-field (char or byte) cutting has some special handling */
  184. if (!(opt & CUT_OPT_FIELDS_FLGS)) {
  185. static const char _op_on_field[] ALIGN1 = " only when operating on fields";
  186. if (opt & CUT_OPT_SUPPRESS_FLGS) {
  187. bb_error_msg_and_die
  188. ("suppressing non-delimited lines makes sense%s",
  189. _op_on_field);
  190. }
  191. if (delim != '\t') {
  192. bb_error_msg_and_die
  193. ("a delimiter may be specified%s", _op_on_field);
  194. }
  195. }
  196. /*
  197. * parse list and put values into startpos and endpos.
  198. * valid list formats: N, N-, N-M, -M
  199. * more than one list can be separated by commas
  200. */
  201. {
  202. char *ntok;
  203. int s = 0, e = 0;
  204. /* take apart the lists, one by one (they are separated with commas) */
  205. while ((ltok = strsep(&sopt, ",")) != NULL) {
  206. /* it's actually legal to pass an empty list */
  207. if (!ltok[0])
  208. continue;
  209. /* get the start pos */
  210. ntok = strsep(&ltok, "-");
  211. if (!ntok[0]) {
  212. s = BOL;
  213. } else {
  214. s = xatoi_positive(ntok);
  215. /* account for the fact that arrays are zero based, while
  216. * the user expects the first char on the line to be char #1 */
  217. if (s != 0)
  218. s--;
  219. }
  220. /* get the end pos */
  221. if (ltok == NULL) {
  222. e = NON_RANGE;
  223. } else if (!ltok[0]) {
  224. e = EOL;
  225. } else {
  226. e = xatoi_positive(ltok);
  227. /* if the user specified and end position of 0,
  228. * that means "til the end of the line" */
  229. if (e == 0)
  230. e = EOL;
  231. e--; /* again, arrays are zero based, lines are 1 based */
  232. if (e == s)
  233. e = NON_RANGE;
  234. }
  235. /* add the new list */
  236. cut_lists = xrealloc_vector(cut_lists, 4, nlists);
  237. /* NB: startpos is always >= 0,
  238. * while endpos may be = NON_RANGE (-1) */
  239. cut_lists[nlists].startpos = s;
  240. cut_lists[nlists].endpos = e;
  241. nlists++;
  242. }
  243. /* make sure we got some cut positions out of all that */
  244. if (nlists == 0)
  245. bb_error_msg_and_die("missing list of positions");
  246. /* now that the lists are parsed, we need to sort them to make life
  247. * easier on us when it comes time to print the chars / fields / lines
  248. */
  249. qsort(cut_lists, nlists, sizeof(cut_lists[0]), cmpfunc);
  250. }
  251. {
  252. int retval = EXIT_SUCCESS;
  253. if (!*argv)
  254. *--argv = (char *)"-";
  255. do {
  256. FILE *file = fopen_or_warn_stdin(*argv);
  257. if (!file) {
  258. retval = EXIT_FAILURE;
  259. continue;
  260. }
  261. cut_file(file, delim, cut_lists, nlists);
  262. fclose_if_not_stdin(file);
  263. } while (*++argv);
  264. if (ENABLE_FEATURE_CLEAN_UP)
  265. free(cut_lists);
  266. fflush_stdout_and_exit(retval);
  267. }
  268. }