sort.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * SuS3 compliant sort implementation for busybox
  4. *
  5. * Copyright (C) 2004 by Rob Landley <rob@landley.net>
  6. *
  7. * MAINTAINER: Rob Landley <rob@landley.net>
  8. *
  9. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  10. *
  11. * See SuS3 sort standard at:
  12. * http://www.opengroup.org/onlinepubs/007904975/utilities/sort.html
  13. */
  14. //config:config SORT
  15. //config: bool "sort (7.4 kb)"
  16. //config: default y
  17. //config: help
  18. //config: sort is used to sort lines of text in specified files.
  19. //config:
  20. //config:config FEATURE_SORT_BIG
  21. //config: bool "Full SuSv3 compliant sort (support -ktcsbdfiozgM)"
  22. //config: default y
  23. //config: depends on SORT
  24. //config: help
  25. //config: Without this, sort only supports -r, -u, and an integer version
  26. //config: of -n. Selecting this adds sort keys, floating point support, and
  27. //config: more. This adds a little over 3k to a nonstatic build on x86.
  28. //config:
  29. //config: The SuSv3 sort standard is available at:
  30. //config: http://www.opengroup.org/onlinepubs/007904975/utilities/sort.html
  31. //applet:IF_SORT(APPLET_NOEXEC(sort, sort, BB_DIR_USR_BIN, BB_SUID_DROP, sort))
  32. //kbuild:lib-$(CONFIG_SORT) += sort.o
  33. //usage:#define sort_trivial_usage
  34. //usage: "[-nru"
  35. //usage: IF_FEATURE_SORT_BIG("gMcszbdfiokt] [-o FILE] [-k start[.offset][opts][,end[.offset][opts]] [-t CHAR")
  36. //usage: "] [FILE]..."
  37. //usage:#define sort_full_usage "\n\n"
  38. //usage: "Sort lines of text\n"
  39. //usage: IF_FEATURE_SORT_BIG(
  40. //usage: "\n -o FILE Output to FILE"
  41. //usage: "\n -c Check whether input is sorted"
  42. //usage: "\n -b Ignore leading blanks"
  43. //usage: "\n -f Ignore case"
  44. //usage: "\n -i Ignore unprintable characters"
  45. //usage: "\n -d Dictionary order (blank or alphanumeric only)"
  46. //usage: "\n -g General numerical sort"
  47. //usage: "\n -M Sort month"
  48. //usage: )
  49. //-h, --human-numeric-sort: compare human readable numbers (e.g., 2K 1G)
  50. //usage: "\n -n Sort numbers"
  51. //usage: IF_FEATURE_SORT_BIG(
  52. //usage: "\n -t CHAR Field separator"
  53. //usage: "\n -k N[,M] Sort by Nth field"
  54. //usage: )
  55. //usage: "\n -r Reverse sort order"
  56. //usage: IF_FEATURE_SORT_BIG(
  57. //usage: "\n -s Stable (don't sort ties alphabetically)"
  58. //usage: )
  59. //usage: "\n -u Suppress duplicate lines"
  60. //usage: IF_FEATURE_SORT_BIG(
  61. //usage: "\n -z Lines are terminated by NUL, not newline"
  62. ////usage: "\n -m Ignored for GNU compatibility"
  63. ////usage: "\n -S BUFSZ Ignored for GNU compatibility"
  64. ////usage: "\n -T TMPDIR Ignored for GNU compatibility"
  65. //usage: )
  66. //usage:
  67. //usage:#define sort_example_usage
  68. //usage: "$ echo -e \"e\\nf\\nb\\nd\\nc\\na\" | sort\n"
  69. //usage: "a\n"
  70. //usage: "b\n"
  71. //usage: "c\n"
  72. //usage: "d\n"
  73. //usage: "e\n"
  74. //usage: "f\n"
  75. //usage: IF_FEATURE_SORT_BIG(
  76. //usage: "$ echo -e \"c 3\\nb 2\\nd 2\" | $SORT -k 2,2n -k 1,1r\n"
  77. //usage: "d 2\n"
  78. //usage: "b 2\n"
  79. //usage: "c 3\n"
  80. //usage: )
  81. //usage: ""
  82. #include "libbb.h"
  83. /* This is a NOEXEC applet. Be very careful! */
  84. /*
  85. sort [-m][-o output][-bdfinru][-t char][-k keydef]... [file...]
  86. sort -c [-bdfinru][-t char][-k keydef][file]
  87. */
  88. /* These are sort types */
  89. #define OPT_STR "ngMucszbrdfimS:T:o:k:*t:"
  90. enum {
  91. FLAG_n = 1, /* Numeric sort */
  92. FLAG_g = 2, /* Sort using strtod() */
  93. FLAG_M = 4, /* Sort date */
  94. /* ucsz apply to root level only, not keys. b at root level implies bb */
  95. FLAG_u = 8, /* Unique */
  96. FLAG_c = 0x10, /* Check: no output, exit(!ordered) */
  97. FLAG_s = 0x20, /* Stable sort, no ascii fallback at end */
  98. FLAG_z = 0x40, /* Input and output is NUL terminated, not \n */
  99. /* These can be applied to search keys, the previous four can't */
  100. FLAG_b = 0x80, /* Ignore leading blanks */
  101. FLAG_r = 0x100, /* Reverse */
  102. FLAG_d = 0x200, /* Ignore !(isalnum()|isspace()) */
  103. FLAG_f = 0x400, /* Force uppercase */
  104. FLAG_i = 0x800, /* Ignore !isprint() */
  105. FLAG_m = 0x1000, /* ignored: merge already sorted files; do not sort */
  106. FLAG_S = 0x2000, /* ignored: -S, --buffer-size=SIZE */
  107. FLAG_T = 0x4000, /* ignored: -T, --temporary-directory=DIR */
  108. FLAG_o = 0x8000,
  109. FLAG_k = 0x10000,
  110. FLAG_t = 0x20000,
  111. FLAG_bb = 0x80000000, /* Ignore trailing blanks */
  112. };
  113. #if ENABLE_FEATURE_SORT_BIG
  114. static char key_separator;
  115. static struct sort_key {
  116. struct sort_key *next_key; /* linked list */
  117. unsigned range[4]; /* start word, start char, end word, end char */
  118. unsigned flags;
  119. } *key_list;
  120. static char *get_key(char *str, struct sort_key *key, int flags)
  121. {
  122. int start = start; /* for compiler */
  123. int end;
  124. int len, j;
  125. unsigned i;
  126. /* Special case whole string, so we don't have to make a copy */
  127. if (key->range[0] == 1 && !key->range[1] && !key->range[2] && !key->range[3]
  128. && !(flags & (FLAG_b | FLAG_d | FLAG_f | FLAG_i | FLAG_bb))
  129. ) {
  130. return str;
  131. }
  132. /* Find start of key on first pass, end on second pass */
  133. len = strlen(str);
  134. for (j = 0; j < 2; j++) {
  135. if (!key->range[2*j])
  136. end = len;
  137. /* Loop through fields */
  138. else {
  139. unsigned char ch = 0;
  140. end = 0;
  141. for (i = 1; i < key->range[2*j] + j; i++) {
  142. if (key_separator) {
  143. /* Skip body of key and separator */
  144. while ((ch = str[end]) != '\0') {
  145. end++;
  146. if (ch == key_separator)
  147. break;
  148. }
  149. } else {
  150. /* Skip leading blanks */
  151. while (isspace(str[end]))
  152. end++;
  153. /* Skip body of key */
  154. while (str[end] != '\0') {
  155. if (isspace(str[end]))
  156. break;
  157. end++;
  158. }
  159. }
  160. }
  161. /* Remove last delim: "abc:def:" => "abc:def" */
  162. if (j && ch) {
  163. //if (str[end-1] != key_separator)
  164. // bb_error_msg(_and_die("BUG! "
  165. // "str[start:%d,end:%d]:'%.*s'",
  166. // start, end, (int)(end-start), &str[start]);
  167. end--;
  168. }
  169. }
  170. if (!j) start = end;
  171. }
  172. /* Strip leading whitespace if necessary */
  173. if (flags & FLAG_b)
  174. /* not using skip_whitespace() for speed */
  175. while (isspace(str[start])) start++;
  176. /* Strip trailing whitespace if necessary */
  177. if (flags & FLAG_bb)
  178. while (end > start && isspace(str[end-1])) end--;
  179. /* -kSTART,N.ENDCHAR: honor ENDCHAR (1-based) */
  180. if (key->range[3]) {
  181. end = key->range[3];
  182. if (end > len) end = len;
  183. }
  184. /* -kN.STARTCHAR[,...]: honor STARTCHAR (1-based) */
  185. if (key->range[1]) {
  186. start += key->range[1] - 1;
  187. if (start > len) start = len;
  188. }
  189. /* Make the copy */
  190. if (end < start)
  191. end = start;
  192. str = xstrndup(str+start, end-start);
  193. /* Handle -d */
  194. if (flags & FLAG_d) {
  195. for (start = end = 0; str[end]; end++)
  196. if (isspace(str[end]) || isalnum(str[end]))
  197. str[start++] = str[end];
  198. str[start] = '\0';
  199. }
  200. /* Handle -i */
  201. if (flags & FLAG_i) {
  202. for (start = end = 0; str[end]; end++)
  203. if (isprint_asciionly(str[end]))
  204. str[start++] = str[end];
  205. str[start] = '\0';
  206. }
  207. /* Handle -f */
  208. if (flags & FLAG_f)
  209. for (i = 0; str[i]; i++)
  210. str[i] = toupper(str[i]);
  211. return str;
  212. }
  213. static struct sort_key *add_key(void)
  214. {
  215. struct sort_key **pkey = &key_list;
  216. while (*pkey)
  217. pkey = &((*pkey)->next_key);
  218. return *pkey = xzalloc(sizeof(struct sort_key));
  219. }
  220. #define GET_LINE(fp) \
  221. ((option_mask32 & FLAG_z) \
  222. ? bb_get_chunk_from_file(fp, NULL) \
  223. : xmalloc_fgetline(fp))
  224. #else
  225. #define GET_LINE(fp) xmalloc_fgetline(fp)
  226. #endif
  227. /* Iterate through keys list and perform comparisons */
  228. static int compare_keys(const void *xarg, const void *yarg)
  229. {
  230. int flags = option_mask32, retval = 0;
  231. char *x, *y;
  232. #if ENABLE_FEATURE_SORT_BIG
  233. struct sort_key *key;
  234. for (key = key_list; !retval && key; key = key->next_key) {
  235. flags = key->flags ? key->flags : option_mask32;
  236. /* Chop out and modify key chunks, handling -dfib */
  237. x = get_key(*(char **)xarg, key, flags);
  238. y = get_key(*(char **)yarg, key, flags);
  239. #else
  240. /* This curly bracket serves no purpose but to match the nesting
  241. * level of the for () loop we're not using */
  242. {
  243. x = *(char **)xarg;
  244. y = *(char **)yarg;
  245. #endif
  246. /* Perform actual comparison */
  247. switch (flags & (FLAG_n | FLAG_M | FLAG_g)) {
  248. default:
  249. bb_error_msg_and_die("unknown sort type");
  250. break;
  251. /* Ascii sort */
  252. case 0:
  253. #if ENABLE_LOCALE_SUPPORT
  254. retval = strcoll(x, y);
  255. #else
  256. retval = strcmp(x, y);
  257. #endif
  258. break;
  259. #if ENABLE_FEATURE_SORT_BIG
  260. case FLAG_g: {
  261. char *xx, *yy;
  262. double dx = strtod(x, &xx);
  263. double dy = strtod(y, &yy);
  264. /* not numbers < NaN < -infinity < numbers < +infinity) */
  265. if (x == xx)
  266. retval = (y == yy ? 0 : -1);
  267. else if (y == yy)
  268. retval = 1;
  269. /* Check for isnan */
  270. else if (dx != dx)
  271. retval = (dy != dy) ? 0 : -1;
  272. else if (dy != dy)
  273. retval = 1;
  274. /* Check for infinity. Could underflow, but it avoids libm. */
  275. else if (1.0 / dx == 0.0) {
  276. if (dx < 0)
  277. retval = (1.0 / dy == 0.0 && dy < 0) ? 0 : -1;
  278. else
  279. retval = (1.0 / dy == 0.0 && dy > 0) ? 0 : 1;
  280. } else if (1.0 / dy == 0.0)
  281. retval = (dy < 0) ? 1 : -1;
  282. else
  283. retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
  284. break;
  285. }
  286. case FLAG_M: {
  287. struct tm thyme;
  288. int dx;
  289. char *xx, *yy;
  290. xx = strptime(x, "%b", &thyme);
  291. dx = thyme.tm_mon;
  292. yy = strptime(y, "%b", &thyme);
  293. if (!xx)
  294. retval = (!yy) ? 0 : -1;
  295. else if (!yy)
  296. retval = 1;
  297. else
  298. retval = dx - thyme.tm_mon;
  299. break;
  300. }
  301. /* Full floating point version of -n */
  302. case FLAG_n: {
  303. double dx = atof(x);
  304. double dy = atof(y);
  305. retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
  306. break;
  307. }
  308. } /* switch */
  309. /* Free key copies. */
  310. if (x != *(char **)xarg) free(x);
  311. if (y != *(char **)yarg) free(y);
  312. /* if (retval) break; - done by for () anyway */
  313. #else
  314. /* Integer version of -n for tiny systems */
  315. case FLAG_n:
  316. retval = atoi(x) - atoi(y);
  317. break;
  318. } /* switch */
  319. #endif
  320. } /* for */
  321. /* Perform fallback sort if necessary */
  322. if (!retval && !(option_mask32 & FLAG_s)) {
  323. flags = option_mask32;
  324. retval = strcmp(*(char **)xarg, *(char **)yarg);
  325. }
  326. if (flags & FLAG_r)
  327. return -retval;
  328. return retval;
  329. }
  330. #if ENABLE_FEATURE_SORT_BIG
  331. static unsigned str2u(char **str)
  332. {
  333. unsigned long lu;
  334. if (!isdigit((*str)[0]))
  335. bb_error_msg_and_die("bad field specification");
  336. lu = strtoul(*str, str, 10);
  337. if ((sizeof(long) > sizeof(int) && lu > INT_MAX) || !lu)
  338. bb_error_msg_and_die("bad field specification");
  339. return lu;
  340. }
  341. #endif
  342. int sort_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  343. int sort_main(int argc UNUSED_PARAM, char **argv)
  344. {
  345. char *line, **lines;
  346. char *str_ignored, *str_o, *str_t;
  347. llist_t *lst_k = NULL;
  348. int i;
  349. int linecount;
  350. unsigned opts;
  351. xfunc_error_retval = 2;
  352. /* Parse command line options */
  353. opts = getopt32(argv, "^"
  354. OPT_STR
  355. "\0" "o--o:t--t"/*-t, -o: at most one of each*/,
  356. &str_ignored, &str_ignored, &str_o, &lst_k, &str_t
  357. );
  358. /* global b strips leading and trailing spaces */
  359. if (opts & FLAG_b)
  360. option_mask32 |= FLAG_bb;
  361. #if ENABLE_FEATURE_SORT_BIG
  362. if (opts & FLAG_t) {
  363. if (!str_t[0] || str_t[1])
  364. bb_error_msg_and_die("bad -t parameter");
  365. key_separator = str_t[0];
  366. }
  367. /* note: below this point we use option_mask32, not opts,
  368. * since that reduces register pressure and makes code smaller */
  369. /* Parse sort key */
  370. while (lst_k) {
  371. enum {
  372. FLAG_allowed_for_k =
  373. FLAG_n | /* Numeric sort */
  374. FLAG_g | /* Sort using strtod() */
  375. FLAG_M | /* Sort date */
  376. FLAG_b | /* Ignore leading blanks */
  377. FLAG_r | /* Reverse */
  378. FLAG_d | /* Ignore !(isalnum()|isspace()) */
  379. FLAG_f | /* Force uppercase */
  380. FLAG_i | /* Ignore !isprint() */
  381. 0
  382. };
  383. struct sort_key *key = add_key();
  384. char *str_k = llist_pop(&lst_k);
  385. i = 0; /* i==0 before comma, 1 after (-k3,6) */
  386. while (*str_k) {
  387. /* Start of range */
  388. /* Cannot use bb_strtou - suffix can be a letter */
  389. key->range[2*i] = str2u(&str_k);
  390. if (*str_k == '.') {
  391. str_k++;
  392. key->range[2*i+1] = str2u(&str_k);
  393. }
  394. while (*str_k) {
  395. int flag;
  396. const char *idx;
  397. if (*str_k == ',' && !i++) {
  398. str_k++;
  399. break;
  400. } /* no else needed: fall through to syntax error
  401. because comma isn't in OPT_STR */
  402. idx = strchr(OPT_STR, *str_k);
  403. if (!idx)
  404. bb_error_msg_and_die("unknown key option");
  405. flag = 1 << (idx - OPT_STR);
  406. if (flag & ~FLAG_allowed_for_k)
  407. bb_error_msg_and_die("unknown sort type");
  408. /* b after ',' means strip _trailing_ space */
  409. if (i && flag == FLAG_b)
  410. flag = FLAG_bb;
  411. key->flags |= flag;
  412. str_k++;
  413. }
  414. }
  415. }
  416. #endif
  417. /* Open input files and read data */
  418. argv += optind;
  419. if (!*argv)
  420. *--argv = (char*)"-";
  421. linecount = 0;
  422. lines = NULL;
  423. do {
  424. /* coreutils 6.9 compat: abort on first open error,
  425. * do not continue to next file: */
  426. FILE *fp = xfopen_stdin(*argv);
  427. for (;;) {
  428. line = GET_LINE(fp);
  429. if (!line)
  430. break;
  431. lines = xrealloc_vector(lines, 6, linecount);
  432. lines[linecount++] = line;
  433. }
  434. fclose_if_not_stdin(fp);
  435. } while (*++argv);
  436. #if ENABLE_FEATURE_SORT_BIG
  437. /* If no key, perform alphabetic sort */
  438. if (!key_list)
  439. add_key()->range[0] = 1;
  440. /* Handle -c */
  441. if (option_mask32 & FLAG_c) {
  442. int j = (option_mask32 & FLAG_u) ? -1 : 0;
  443. for (i = 1; i < linecount; i++) {
  444. if (compare_keys(&lines[i-1], &lines[i]) > j) {
  445. fprintf(stderr, "Check line %u\n", i);
  446. return EXIT_FAILURE;
  447. }
  448. }
  449. return EXIT_SUCCESS;
  450. }
  451. #endif
  452. /* Perform the actual sort */
  453. qsort(lines, linecount, sizeof(lines[0]), compare_keys);
  454. /* Handle -u */
  455. if (option_mask32 & FLAG_u) {
  456. int j = 0;
  457. /* coreutils 6.3 drop lines for which only key is the same */
  458. /* -- disabling last-resort compare... */
  459. option_mask32 |= FLAG_s;
  460. for (i = 1; i < linecount; i++) {
  461. if (compare_keys(&lines[j], &lines[i]) == 0)
  462. free(lines[i]);
  463. else
  464. lines[++j] = lines[i];
  465. }
  466. if (linecount)
  467. linecount = j+1;
  468. }
  469. /* Print it */
  470. #if ENABLE_FEATURE_SORT_BIG
  471. /* Open output file _after_ we read all input ones */
  472. if (option_mask32 & FLAG_o)
  473. xmove_fd(xopen(str_o, O_WRONLY|O_CREAT|O_TRUNC), STDOUT_FILENO);
  474. #endif
  475. {
  476. int ch = (option_mask32 & FLAG_z) ? '\0' : '\n';
  477. for (i = 0; i < linecount; i++)
  478. printf("%s%c", lines[i], ch);
  479. }
  480. fflush_stdout_and_exit(EXIT_SUCCESS);
  481. }