3
0

cut.c 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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 (5.8 kb)"
  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. #define OPT_STR "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 = getopt32(argv, "^"
  180. OPT_STR
  181. "\0" "b--bcf:c--bcf:f--bcf",
  182. &sopt, &sopt, &sopt, &ltok
  183. );
  184. // argc -= optind;
  185. argv += optind;
  186. if (!(opt & (CUT_OPT_BYTE_FLGS | CUT_OPT_CHAR_FLGS | CUT_OPT_FIELDS_FLGS)))
  187. bb_error_msg_and_die("expected a list of bytes, characters, or fields");
  188. if (opt & CUT_OPT_DELIM_FLGS) {
  189. if (ltok[0] && ltok[1]) { /* more than 1 char? */
  190. bb_error_msg_and_die("the delimiter must be a single character");
  191. }
  192. delim = ltok[0];
  193. }
  194. /* non-field (char or byte) cutting has some special handling */
  195. if (!(opt & CUT_OPT_FIELDS_FLGS)) {
  196. static const char _op_on_field[] ALIGN1 = " only when operating on fields";
  197. if (opt & CUT_OPT_SUPPRESS_FLGS) {
  198. bb_error_msg_and_die
  199. ("suppressing non-delimited lines makes sense%s",
  200. _op_on_field);
  201. }
  202. if (delim != '\t') {
  203. bb_error_msg_and_die
  204. ("a delimiter may be specified%s", _op_on_field);
  205. }
  206. }
  207. /*
  208. * parse list and put values into startpos and endpos.
  209. * valid list formats: N, N-, N-M, -M
  210. * more than one list can be separated by commas
  211. */
  212. {
  213. char *ntok;
  214. int s = 0, e = 0;
  215. /* take apart the lists, one by one (they are separated with commas) */
  216. while ((ltok = strsep(&sopt, ",")) != NULL) {
  217. /* it's actually legal to pass an empty list */
  218. if (!ltok[0])
  219. continue;
  220. /* get the start pos */
  221. ntok = strsep(&ltok, "-");
  222. if (!ntok[0]) {
  223. s = BOL;
  224. } else {
  225. s = xatoi_positive(ntok);
  226. /* account for the fact that arrays are zero based, while
  227. * the user expects the first char on the line to be char #1 */
  228. if (s != 0)
  229. s--;
  230. }
  231. /* get the end pos */
  232. if (ltok == NULL) {
  233. e = NON_RANGE;
  234. } else if (!ltok[0]) {
  235. e = EOL;
  236. } else {
  237. e = xatoi_positive(ltok);
  238. /* if the user specified and end position of 0,
  239. * that means "til the end of the line" */
  240. if (e == 0)
  241. e = EOL;
  242. e--; /* again, arrays are zero based, lines are 1 based */
  243. if (e == s)
  244. e = NON_RANGE;
  245. }
  246. /* add the new list */
  247. cut_lists = xrealloc_vector(cut_lists, 4, nlists);
  248. /* NB: startpos is always >= 0,
  249. * while endpos may be = NON_RANGE (-1) */
  250. cut_lists[nlists].startpos = s;
  251. cut_lists[nlists].endpos = e;
  252. nlists++;
  253. }
  254. /* make sure we got some cut positions out of all that */
  255. if (nlists == 0)
  256. bb_error_msg_and_die("missing list of positions");
  257. /* now that the lists are parsed, we need to sort them to make life
  258. * easier on us when it comes time to print the chars / fields / lines
  259. */
  260. qsort(cut_lists, nlists, sizeof(cut_lists[0]), cmpfunc);
  261. }
  262. {
  263. int retval = EXIT_SUCCESS;
  264. if (!*argv)
  265. *--argv = (char *)"-";
  266. do {
  267. FILE *file = fopen_or_warn_stdin(*argv);
  268. if (!file) {
  269. retval = EXIT_FAILURE;
  270. continue;
  271. }
  272. cut_file(file, delim, cut_lists, nlists);
  273. fclose_if_not_stdin(file);
  274. } while (*++argv);
  275. if (ENABLE_FEATURE_CLEAN_UP)
  276. free(cut_lists);
  277. fflush_stdout_and_exit(retval);
  278. }
  279. }