cut.c 9.6 KB

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