cut.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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 (6.7 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: "{-b|c LIST | -f"IF_FEATURE_CUT_REGEX("|F")" LIST [-d SEP] [-s]} [-D] [-O SEP] [FILE]..."
  28. // --output-delimiter SEP is too long to fit into 80 char-wide help ----------------^^^^^^^^
  29. //usage:#define cut_full_usage "\n\n"
  30. //usage: "Print selected fields from FILEs to stdout\n"
  31. //usage: "\n -b LIST Output only bytes from LIST"
  32. //usage: "\n -c LIST Output only characters from LIST"
  33. //usage: IF_FEATURE_CUT_REGEX(
  34. //usage: "\n -d SEP Input field delimiter (default -f TAB, -F run of whitespace)"
  35. //usage: ) IF_NOT_FEATURE_CUT_REGEX(
  36. //usage: "\n -d SEP Input field delimiter (default TAB)"
  37. //usage: )
  38. //usage: "\n -f LIST Print only these fields (-d is single char)"
  39. //usage: IF_FEATURE_CUT_REGEX(
  40. //usage: "\n -F LIST Print only these fields (-d is regex)"
  41. //usage: )
  42. //usage: "\n -s Drop lines with no delimiter (else print them in full)"
  43. //usage: "\n -D Don't sort ranges; line without delimiters has one field"
  44. //usage: IF_LONG_OPTS(
  45. //usage: "\n --output-delimiter SEP Output field delimeter"
  46. //usage: ) IF_NOT_LONG_OPTS(
  47. //usage: IF_FEATURE_CUT_REGEX(
  48. //usage: "\n -O SEP Output field delimeter (default = -d for -f, one space for -F)"
  49. //usage: ) IF_NOT_FEATURE_CUT_REGEX(
  50. //usage: "\n -O SEP Output field delimeter (default = -d)"
  51. //usage: )
  52. //usage: )
  53. //usage: "\n -n Ignored"
  54. //(manpage:-n with -b: don't split multibyte characters)
  55. //usage:
  56. //usage:#define cut_example_usage
  57. //usage: "$ echo \"Hello world\" | cut -f 1 -d ' '\n"
  58. //usage: "Hello\n"
  59. //usage: "$ echo \"Hello world\" | cut -f 2 -d ' '\n"
  60. //usage: "world\n"
  61. #include "libbb.h"
  62. #if ENABLE_FEATURE_CUT_REGEX
  63. #include "xregex.h"
  64. #endif
  65. /* This is a NOEXEC applet. Be very careful! */
  66. /* option vars */
  67. #define OPT_STR "b:c:f:d:O:sD"IF_FEATURE_CUT_REGEX("F:")"n"
  68. #define OPT_BYTE (1 << 0)
  69. #define OPT_CHAR (1 << 1)
  70. #define OPT_FIELDS (1 << 2)
  71. #define OPT_DELIM (1 << 3)
  72. #define OPT_ODELIM (1 << 4)
  73. #define OPT_SUPPRESS (1 << 5)
  74. #define OPT_NOSORT (1 << 6)
  75. #define OPT_REGEX ((1 << 7) * ENABLE_FEATURE_CUT_REGEX)
  76. #define opt_REGEX (option_mask32 & OPT_REGEX)
  77. struct cut_range {
  78. unsigned startpos;
  79. unsigned endpos;
  80. };
  81. static int cmpfunc(const void *a, const void *b)
  82. {
  83. const struct cut_range *aa = a;
  84. const struct cut_range *bb = b;
  85. return aa->startpos - bb->startpos;
  86. }
  87. #define END_OF_LIST(list_elem) ((list_elem).startpos == UINT_MAX)
  88. #define NOT_END_OF_LIST(list_elem) ((list_elem).startpos != UINT_MAX)
  89. static void cut_file(FILE *file, const char *delim, const char *odelim,
  90. const struct cut_range *cut_list)
  91. {
  92. char *line;
  93. unsigned linenum = 0; /* keep these zero-based to be consistent */
  94. int first_print = 1;
  95. /* go through every line in the file */
  96. while ((line = xmalloc_fgetline(file)) != NULL) {
  97. /* set up a list so we can keep track of what's been printed */
  98. unsigned linelen = strlen(line);
  99. unsigned cl_pos = 0;
  100. /* Cut based on chars/bytes XXX: only works when sizeof(char) == byte */
  101. if (option_mask32 & (OPT_CHAR | OPT_BYTE)) {
  102. char *printed = xzalloc(linelen + 1);
  103. int need_odelim = 0;
  104. /* print the chars specified in each cut list */
  105. for (; NOT_END_OF_LIST(cut_list[cl_pos]); cl_pos++) {
  106. unsigned spos = cut_list[cl_pos].startpos;
  107. while (spos < linelen) {
  108. if (!printed[spos]) {
  109. printed[spos] = 'X';
  110. if (need_odelim && spos != 0 && !printed[spos-1]) {
  111. need_odelim = 0;
  112. fputs_stdout(odelim);
  113. }
  114. putchar(line[spos]);
  115. }
  116. spos++;
  117. if (spos > cut_list[cl_pos].endpos) {
  118. /* will print OSEP (if not empty) */
  119. need_odelim = (odelim && odelim[0]);
  120. break;
  121. }
  122. }
  123. }
  124. free(printed);
  125. /* Cut by lines */
  126. } else if (!opt_REGEX && *delim == '\n') {
  127. unsigned spos = cut_list[cl_pos].startpos;
  128. linenum++;
  129. /* get out if we have no more ranges to process or if the lines
  130. * are lower than what we're interested in */
  131. if (linenum <= spos || END_OF_LIST(cut_list[cl_pos]))
  132. goto next_line;
  133. /* if the line we're looking for is lower than the one we were
  134. * passed, it means we displayed it already, so move on */
  135. while (++spos < linenum) {
  136. /* go to the next list if we're at the end of this one */
  137. if (spos > cut_list[cl_pos].endpos) {
  138. cl_pos++;
  139. /* get out if there's no more ranges to process */
  140. if (END_OF_LIST(cut_list[cl_pos]))
  141. goto next_line;
  142. spos = cut_list[cl_pos].startpos;
  143. /* get out if the current line is lower than the one
  144. * we just became interested in */
  145. if (linenum <= spos)
  146. goto next_line;
  147. }
  148. }
  149. /* If we made it here, it means we've found the line we're
  150. * looking for, so print it */
  151. if (first_print) {
  152. first_print = 0;
  153. fputs_stdout(line);
  154. } else
  155. printf("%s%s", odelim, line);
  156. goto next_line;
  157. /* Cut by fields */
  158. } else {
  159. unsigned next = 0, start = 0, end = 0;
  160. unsigned dcount = 0; /* we saw Nth delimiter (0 - didn't see any yet) */
  161. /* Blank line? Check -s (later check for -s does not catch empty lines) */
  162. if (linelen == 0) {
  163. if (option_mask32 & OPT_SUPPRESS)
  164. goto next_line;
  165. }
  166. if (!odelim)
  167. odelim = "\t";
  168. first_print = 1;
  169. /* Loop through bytes, finding next delimiter */
  170. for (;;) {
  171. /* End of current range? */
  172. if (end == linelen || dcount > cut_list[cl_pos].endpos) {
  173. end_of_range:
  174. cl_pos++;
  175. if (END_OF_LIST(cut_list[cl_pos]))
  176. break;
  177. if (option_mask32 & OPT_NOSORT)
  178. start = dcount = next = 0;
  179. end = 0; /* (why?) */
  180. //bb_error_msg("End of current range");
  181. }
  182. /* End of current line? */
  183. if (next == linelen) {
  184. end = linelen; /* print up to end */
  185. /* If we've seen no delimiters, and no -D, check -s */
  186. if (!(option_mask32 & OPT_NOSORT) && cl_pos == 0 && dcount == 0) {
  187. if (option_mask32 & OPT_SUPPRESS)
  188. goto next_line;
  189. /* else: will print entire line */
  190. } else if (dcount < cut_list[cl_pos].startpos) {
  191. /* echo 1.2 | cut -d. -f1,3: prints "1", not "1." */
  192. //break;
  193. /* ^^^ this fails a case with -D:
  194. * echo 1 2 | cut -DF 1,3,2:
  195. * do not end line processing when didn't find field#3
  196. */
  197. //if (option_mask32 & OPT_NOSORT) - no, just do it always
  198. goto end_of_range;
  199. }
  200. //bb_error_msg("End of current line: s:%d e:%d", start, end);
  201. } else {
  202. /* Find next delimiter */
  203. #if ENABLE_FEATURE_CUT_REGEX
  204. if (opt_REGEX) {
  205. regmatch_t rr;
  206. regex_t *reg = (void*) delim;
  207. if (regexec(reg, line + next, 1, &rr, REG_NOTBOL|REG_NOTEOL) != 0) {
  208. /* not found, go to "end of line" logic */
  209. next = linelen;
  210. continue;
  211. }
  212. end = next + rr.rm_so;
  213. next += (rr.rm_eo ? rr.rm_eo : 1);
  214. /* ^^^ advancing by at least 1 prevents infinite loops */
  215. /* testcase: echo "no at sign" | cut -d'@*' -F 1- */
  216. } else
  217. #endif
  218. {
  219. end = next++;
  220. if (line[end] != *delim)
  221. continue;
  222. }
  223. /* Got delimiter */
  224. dcount++;
  225. if (dcount <= cut_list[cl_pos].startpos) {
  226. /* Not yet within range - loop */
  227. start = next;
  228. continue;
  229. }
  230. /* -F N-M preserves intermediate delimiters: */
  231. //printf "1 2 3 4 5 6 7\n" | toybox cut -O: -F2,4-6,7
  232. //2:4 5 6:7
  233. if (opt_REGEX && dcount <= cut_list[cl_pos].endpos)
  234. continue;
  235. // NB: toybox does the above for -f too, but it's a compatibility bug:
  236. //printf "1 2 3 4 5 6 7 8\n" | toybox cut -d' ' -O: -f2,4-6,7
  237. //2:4 5 6:7 // WRONG!
  238. //printf "1 2 3 4 5 6 7 8\n" | cut -d' ' --output-delimiter=: -f2,4-6,7
  239. //2:4:5:6:7 // GNU coreutils 9.1
  240. }
  241. #if ENABLE_FEATURE_CUT_REGEX
  242. if (end != start || !opt_REGEX)
  243. #endif
  244. {
  245. if (first_print) {
  246. first_print = 0;
  247. printf("%.*s", end - start, line + start);
  248. } else
  249. printf("%s%.*s", odelim, end - start, line + start);
  250. }
  251. start = next;
  252. //if (dcount == 0)
  253. // break; - why?
  254. } /* byte loop */
  255. }
  256. /* if we printed anything, finish with newline */
  257. putchar('\n');
  258. next_line:
  259. free(line);
  260. } /* while (got line) */
  261. /* For -d$'\n' --output-delimiter=^, the overall output is still terminated with \n, not ^ */
  262. if (!opt_REGEX && *delim == '\n' && !first_print)
  263. putchar('\n');
  264. }
  265. int cut_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  266. int cut_main(int argc UNUSED_PARAM, char **argv)
  267. {
  268. /* growable array holding a series of ranges */
  269. struct cut_range *cut_list = NULL;
  270. unsigned nranges = 0; /* number of elements in above list */
  271. char *LIST, *ltok;
  272. const char *delim = NULL;
  273. const char *odelim = NULL;
  274. unsigned opt;
  275. #if ENABLE_FEATURE_CUT_REGEX
  276. regex_t reg;
  277. #endif
  278. #if ENABLE_LONG_OPTS
  279. static const char cut_longopts[] ALIGN1 =
  280. "output-delimiter\0" Required_argument "O"
  281. ;
  282. #endif
  283. #define ARG "bcf"IF_FEATURE_CUT_REGEX("F")
  284. #if ENABLE_LONG_OPTS
  285. opt = getopt32long
  286. #else
  287. opt = getopt32
  288. #endif
  289. (argv, "^"
  290. OPT_STR // = "b:c:f:d:O:sD"IF_FEATURE_CUT_REGEX("F:")"n"
  291. "\0" "b:c:f:" IF_FEATURE_CUT_REGEX("F:") /* one of -bcfF is required */
  292. "b--"ARG":c--"ARG":f--"ARG IF_FEATURE_CUT_REGEX(":F--"ARG), /* they are mutually exclusive */
  293. IF_LONG_OPTS(cut_longopts,)
  294. &LIST, &LIST, &LIST, &delim, &odelim IF_FEATURE_CUT_REGEX(, &LIST)
  295. );
  296. if (!odelim)
  297. odelim = (opt & OPT_REGEX) ? " " : delim;
  298. if (!delim)
  299. delim = (opt & OPT_REGEX) ? "[[:space:]]+" : "\t";
  300. // argc -= optind;
  301. argv += optind;
  302. //if (!(opt & (OPT_BYTE | OPT_CHAR | OPT_FIELDS | OPT_REGEX)))
  303. // bb_simple_error_msg_and_die("expected a list of bytes, characters, or fields");
  304. //^^^ handled by getopt32
  305. /* non-field (char or byte) cutting has some special handling */
  306. if (!(opt & (OPT_FIELDS|OPT_REGEX))) {
  307. static const char requires_f[] ALIGN1 = " requires -f"
  308. IF_FEATURE_CUT_REGEX(" or -F");
  309. if (opt & OPT_SUPPRESS)
  310. bb_error_msg_and_die("-s%s", requires_f);
  311. if (opt & OPT_DELIM)
  312. bb_error_msg_and_die("-d DELIM%s", requires_f);
  313. }
  314. /*
  315. * parse list and put values into startpos and endpos.
  316. * valid range formats: N, N-, N-M, -M
  317. * more than one range can be separated by commas
  318. */
  319. /* take apart the ranges, one by one (separated with commas) */
  320. while ((ltok = strsep(&LIST, ",")) != NULL) {
  321. char *ntok;
  322. int s, e;
  323. /* it's actually legal to pass an empty list */
  324. //if (!ltok[0])
  325. // continue;
  326. //^^^ testcase?
  327. /* get the start pos */
  328. ntok = strsep(&ltok, "-");
  329. if (!ntok[0]) {
  330. if (!ltok) /* testcase: -f '' */
  331. bb_show_usage();
  332. if (!ltok[0]) /* testcase: -f - */
  333. bb_show_usage();
  334. s = 0; /* "-M" means "1-M" */
  335. } else {
  336. /* "N" or "N-[M]" */
  337. /* arrays are zero based, while the user expects
  338. * the first field/char on the line to be char #1 */
  339. s = xatoi_positive(ntok) - 1;
  340. }
  341. /* get the end pos */
  342. if (!ltok) {
  343. e = s; /* "N" means "N-N" */
  344. } else if (!ltok[0]) {
  345. /* "N-" means "until the end of the line" */
  346. e = INT_MAX;
  347. } else {
  348. /* again, arrays are zero based, fields are 1 based */
  349. e = xatoi_positive(ltok) - 1;
  350. }
  351. if (s < 0 || e < s)
  352. bb_error_msg_and_die("invalid range %s-%s", ntok, ltok ?: ntok);
  353. /* add the new range */
  354. cut_list = xrealloc_vector(cut_list, 4, nranges);
  355. /* NB: s is always >= 0 */
  356. cut_list[nranges].startpos = s;
  357. cut_list[nranges].endpos = e;
  358. nranges++;
  359. }
  360. cut_list[nranges].startpos = UINT_MAX; /* end indicator */
  361. /* make sure we got some cut positions out of all that */
  362. //if (nranges == 0)
  363. // bb_simple_error_msg_and_die("missing list of positions");
  364. //^^^ this is impossible since one of -bcfF is required,
  365. // they populate LIST with non-NULL string and when it is parsed,
  366. // cut_list[] gets at least one element.
  367. /* now that the lists are parsed, we need to sort them to make life
  368. * easier on us when it comes time to print the chars / fields / lines
  369. */
  370. if (!(opt & OPT_NOSORT))
  371. qsort(cut_list, nranges, sizeof(cut_list[0]), cmpfunc);
  372. #if ENABLE_FEATURE_CUT_REGEX
  373. if (opt & OPT_REGEX) {
  374. xregcomp(&reg, delim, REG_EXTENDED);
  375. delim = (void*) &reg;
  376. }
  377. #endif
  378. {
  379. exitcode_t retval = EXIT_SUCCESS;
  380. if (!*argv)
  381. *--argv = (char *)"-";
  382. do {
  383. FILE *file = fopen_or_warn_stdin(*argv);
  384. if (!file) {
  385. retval = EXIT_FAILURE;
  386. continue;
  387. }
  388. cut_file(file, delim, odelim, cut_list);
  389. fclose_if_not_stdin(file);
  390. } while (*++argv);
  391. if (ENABLE_FEATURE_CLEAN_UP)
  392. free(cut_list);
  393. fflush_stdout_and_exit(retval);
  394. }
  395. }