sort.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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 -k Sort key"
  28. //usage: "\n -M Sort month"
  29. //usage: )
  30. //usage: "\n -n Sort numbers"
  31. //usage: IF_FEATURE_SORT_BIG(
  32. //usage: "\n -o Output to file"
  33. //usage: "\n -k Sort by key"
  34. //usage: "\n -t CHAR Key separator"
  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 = 0, end = 0, len, j;
  101. unsigned i;
  102. /* Special case whole string, so we don't have to make a copy */
  103. if (key->range[0] == 1 && !key->range[1] && !key->range[2] && !key->range[3]
  104. && !(flags & (FLAG_b | FLAG_d | FLAG_f | FLAG_i | FLAG_bb))
  105. ) {
  106. return str;
  107. }
  108. /* Find start of key on first pass, end on second pass */
  109. len = strlen(str);
  110. for (j = 0; j < 2; j++) {
  111. if (!key->range[2*j])
  112. end = len;
  113. /* Loop through fields */
  114. else {
  115. end = 0;
  116. for (i = 1; i < key->range[2*j] + j; i++) {
  117. if (key_separator) {
  118. /* Skip body of key and separator */
  119. while (str[end]) {
  120. if (str[end++] == key_separator)
  121. break;
  122. }
  123. } else {
  124. /* Skip leading blanks */
  125. while (isspace(str[end]))
  126. end++;
  127. /* Skip body of key */
  128. while (str[end]) {
  129. if (isspace(str[end]))
  130. break;
  131. end++;
  132. }
  133. }
  134. }
  135. }
  136. if (!j) start = end;
  137. }
  138. /* Strip leading whitespace if necessary */
  139. //XXX: skip_whitespace()
  140. if (flags & FLAG_b)
  141. while (isspace(str[start])) start++;
  142. /* Strip trailing whitespace if necessary */
  143. if (flags & FLAG_bb)
  144. while (end > start && isspace(str[end-1])) end--;
  145. /* Handle offsets on start and end */
  146. if (key->range[3]) {
  147. end += key->range[3] - 1;
  148. if (end > len) end = len;
  149. }
  150. if (key->range[1]) {
  151. start += key->range[1] - 1;
  152. if (start > len) start = len;
  153. }
  154. /* Make the copy */
  155. if (end < start) end = start;
  156. str = xstrndup(str+start, end-start);
  157. /* Handle -d */
  158. if (flags & FLAG_d) {
  159. for (start = end = 0; str[end]; end++)
  160. if (isspace(str[end]) || isalnum(str[end]))
  161. str[start++] = str[end];
  162. str[start] = '\0';
  163. }
  164. /* Handle -i */
  165. if (flags & FLAG_i) {
  166. for (start = end = 0; str[end]; end++)
  167. if (isprint_asciionly(str[end]))
  168. str[start++] = str[end];
  169. str[start] = '\0';
  170. }
  171. /* Handle -f */
  172. if (flags & FLAG_f)
  173. for (i = 0; str[i]; i++)
  174. str[i] = toupper(str[i]);
  175. return str;
  176. }
  177. static struct sort_key *add_key(void)
  178. {
  179. struct sort_key **pkey = &key_list;
  180. while (*pkey)
  181. pkey = &((*pkey)->next_key);
  182. return *pkey = xzalloc(sizeof(struct sort_key));
  183. }
  184. #define GET_LINE(fp) \
  185. ((option_mask32 & FLAG_z) \
  186. ? bb_get_chunk_from_file(fp, NULL) \
  187. : xmalloc_fgetline(fp))
  188. #else
  189. #define GET_LINE(fp) xmalloc_fgetline(fp)
  190. #endif
  191. /* Iterate through keys list and perform comparisons */
  192. static int compare_keys(const void *xarg, const void *yarg)
  193. {
  194. int flags = option_mask32, retval = 0;
  195. char *x, *y;
  196. #if ENABLE_FEATURE_SORT_BIG
  197. struct sort_key *key;
  198. for (key = key_list; !retval && key; key = key->next_key) {
  199. flags = key->flags ? key->flags : option_mask32;
  200. /* Chop out and modify key chunks, handling -dfib */
  201. x = get_key(*(char **)xarg, key, flags);
  202. y = get_key(*(char **)yarg, key, flags);
  203. #else
  204. /* This curly bracket serves no purpose but to match the nesting
  205. level of the for () loop we're not using */
  206. {
  207. x = *(char **)xarg;
  208. y = *(char **)yarg;
  209. #endif
  210. /* Perform actual comparison */
  211. switch (flags & 7) {
  212. default:
  213. bb_error_msg_and_die("unknown sort type");
  214. break;
  215. /* Ascii sort */
  216. case 0:
  217. #if ENABLE_LOCALE_SUPPORT
  218. retval = strcoll(x, y);
  219. #else
  220. retval = strcmp(x, y);
  221. #endif
  222. break;
  223. #if ENABLE_FEATURE_SORT_BIG
  224. case FLAG_g: {
  225. char *xx, *yy;
  226. double dx = strtod(x, &xx);
  227. double dy = strtod(y, &yy);
  228. /* not numbers < NaN < -infinity < numbers < +infinity) */
  229. if (x == xx)
  230. retval = (y == yy ? 0 : -1);
  231. else if (y == yy)
  232. retval = 1;
  233. /* Check for isnan */
  234. else if (dx != dx)
  235. retval = (dy != dy) ? 0 : -1;
  236. else if (dy != dy)
  237. retval = 1;
  238. /* Check for infinity. Could underflow, but it avoids libm. */
  239. else if (1.0 / dx == 0.0) {
  240. if (dx < 0)
  241. retval = (1.0 / dy == 0.0 && dy < 0) ? 0 : -1;
  242. else
  243. retval = (1.0 / dy == 0.0 && dy > 0) ? 0 : 1;
  244. } else if (1.0 / dy == 0.0)
  245. retval = (dy < 0) ? 1 : -1;
  246. else
  247. retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
  248. break;
  249. }
  250. case FLAG_M: {
  251. struct tm thyme;
  252. int dx;
  253. char *xx, *yy;
  254. xx = strptime(x, "%b", &thyme);
  255. dx = thyme.tm_mon;
  256. yy = strptime(y, "%b", &thyme);
  257. if (!xx)
  258. retval = (!yy) ? 0 : -1;
  259. else if (!yy)
  260. retval = 1;
  261. else
  262. retval = (dx == thyme.tm_mon) ? 0 : dx - thyme.tm_mon;
  263. break;
  264. }
  265. /* Full floating point version of -n */
  266. case FLAG_n: {
  267. double dx = atof(x);
  268. double dy = atof(y);
  269. retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
  270. break;
  271. }
  272. } /* switch */
  273. /* Free key copies. */
  274. if (x != *(char **)xarg) free(x);
  275. if (y != *(char **)yarg) free(y);
  276. /* if (retval) break; - done by for () anyway */
  277. #else
  278. /* Integer version of -n for tiny systems */
  279. case FLAG_n:
  280. retval = atoi(x) - atoi(y);
  281. break;
  282. } /* switch */
  283. #endif
  284. } /* for */
  285. /* Perform fallback sort if necessary */
  286. if (!retval && !(option_mask32 & FLAG_s))
  287. retval = strcmp(*(char **)xarg, *(char **)yarg);
  288. if (flags & FLAG_r) return -retval;
  289. return retval;
  290. }
  291. #if ENABLE_FEATURE_SORT_BIG
  292. static unsigned str2u(char **str)
  293. {
  294. unsigned long lu;
  295. if (!isdigit((*str)[0]))
  296. bb_error_msg_and_die("bad field specification");
  297. lu = strtoul(*str, str, 10);
  298. if ((sizeof(long) > sizeof(int) && lu > INT_MAX) || !lu)
  299. bb_error_msg_and_die("bad field specification");
  300. return lu;
  301. }
  302. #endif
  303. int sort_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  304. int sort_main(int argc UNUSED_PARAM, char **argv)
  305. {
  306. char *line, **lines;
  307. char *str_ignored, *str_o, *str_t;
  308. llist_t *lst_k = NULL;
  309. int i, flag;
  310. int linecount;
  311. unsigned opts;
  312. xfunc_error_retval = 2;
  313. /* Parse command line options */
  314. /* -o and -t can be given at most once */
  315. opt_complementary = "o--o:t--t:" /* -t, -o: at most one of each */
  316. "k::"; /* -k takes list */
  317. opts = getopt32(argv, OPT_STR, &str_ignored, &str_ignored, &str_o, &lst_k, &str_t);
  318. /* global b strips leading and trailing spaces */
  319. if (opts & FLAG_b)
  320. option_mask32 |= FLAG_bb;
  321. #if ENABLE_FEATURE_SORT_BIG
  322. if (opts & FLAG_t) {
  323. if (!str_t[0] || str_t[1])
  324. bb_error_msg_and_die("bad -t parameter");
  325. key_separator = str_t[0];
  326. }
  327. /* note: below this point we use option_mask32, not opts,
  328. * since that reduces register pressure and makes code smaller */
  329. /* parse sort key */
  330. while (lst_k) {
  331. enum {
  332. FLAG_allowed_for_k =
  333. FLAG_n | /* Numeric sort */
  334. FLAG_g | /* Sort using strtod() */
  335. FLAG_M | /* Sort date */
  336. FLAG_b | /* Ignore leading blanks */
  337. FLAG_r | /* Reverse */
  338. FLAG_d | /* Ignore !(isalnum()|isspace()) */
  339. FLAG_f | /* Force uppercase */
  340. FLAG_i | /* Ignore !isprint() */
  341. 0
  342. };
  343. struct sort_key *key = add_key();
  344. char *str_k = llist_pop(&lst_k);
  345. i = 0; /* i==0 before comma, 1 after (-k3,6) */
  346. while (*str_k) {
  347. /* Start of range */
  348. /* Cannot use bb_strtou - suffix can be a letter */
  349. key->range[2*i] = str2u(&str_k);
  350. if (*str_k == '.') {
  351. str_k++;
  352. key->range[2*i+1] = str2u(&str_k);
  353. }
  354. while (*str_k) {
  355. const char *temp2;
  356. if (*str_k == ',' && !i++) {
  357. str_k++;
  358. break;
  359. } /* no else needed: fall through to syntax error
  360. because comma isn't in OPT_STR */
  361. temp2 = strchr(OPT_STR, *str_k);
  362. if (!temp2)
  363. bb_error_msg_and_die("unknown key option");
  364. flag = 1 << (temp2 - OPT_STR);
  365. if (flag & ~FLAG_allowed_for_k)
  366. bb_error_msg_and_die("unknown sort type");
  367. /* b after ',' means strip _trailing_ space */
  368. if (i && flag == FLAG_b)
  369. flag = FLAG_bb;
  370. key->flags |= flag;
  371. str_k++;
  372. }
  373. }
  374. }
  375. #endif
  376. /* Open input files and read data */
  377. argv += optind;
  378. if (!*argv)
  379. *--argv = (char*)"-";
  380. linecount = 0;
  381. lines = NULL;
  382. do {
  383. /* coreutils 6.9 compat: abort on first open error,
  384. * do not continue to next file: */
  385. FILE *fp = xfopen_stdin(*argv);
  386. for (;;) {
  387. line = GET_LINE(fp);
  388. if (!line)
  389. break;
  390. lines = xrealloc_vector(lines, 6, linecount);
  391. lines[linecount++] = line;
  392. }
  393. fclose_if_not_stdin(fp);
  394. } while (*++argv);
  395. #if ENABLE_FEATURE_SORT_BIG
  396. /* if no key, perform alphabetic sort */
  397. if (!key_list)
  398. add_key()->range[0] = 1;
  399. /* handle -c */
  400. if (option_mask32 & FLAG_c) {
  401. int j = (option_mask32 & FLAG_u) ? -1 : 0;
  402. for (i = 1; i < linecount; i++) {
  403. if (compare_keys(&lines[i-1], &lines[i]) > j) {
  404. fprintf(stderr, "Check line %u\n", i);
  405. return EXIT_FAILURE;
  406. }
  407. }
  408. return EXIT_SUCCESS;
  409. }
  410. #endif
  411. /* Perform the actual sort */
  412. qsort(lines, linecount, sizeof(lines[0]), compare_keys);
  413. /* handle -u */
  414. if (option_mask32 & FLAG_u) {
  415. flag = 0;
  416. /* coreutils 6.3 drop lines for which only key is the same */
  417. /* -- disabling last-resort compare... */
  418. option_mask32 |= FLAG_s;
  419. for (i = 1; i < linecount; i++) {
  420. if (compare_keys(&lines[flag], &lines[i]) == 0)
  421. free(lines[i]);
  422. else
  423. lines[++flag] = lines[i];
  424. }
  425. if (linecount)
  426. linecount = flag+1;
  427. }
  428. /* Print it */
  429. #if ENABLE_FEATURE_SORT_BIG
  430. /* Open output file _after_ we read all input ones */
  431. if (option_mask32 & FLAG_o)
  432. xmove_fd(xopen(str_o, O_WRONLY|O_CREAT|O_TRUNC), STDOUT_FILENO);
  433. #endif
  434. flag = (option_mask32 & FLAG_z) ? '\0' : '\n';
  435. for (i = 0; i < linecount; i++)
  436. printf("%s%c", lines[i], flag);
  437. fflush_stdout_and_exit(EXIT_SUCCESS);
  438. }