sort.c 13 KB

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