cut.c 8.7 KB

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