sort.c 13 KB

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