sort.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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 & (FLAG_n | FLAG_M | FLAG_g)) {
  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. flags = option_mask32;
  289. }
  290. if (flags & FLAG_r)
  291. return -retval;
  292. return retval;
  293. }
  294. #if ENABLE_FEATURE_SORT_BIG
  295. static unsigned str2u(char **str)
  296. {
  297. unsigned long lu;
  298. if (!isdigit((*str)[0]))
  299. bb_error_msg_and_die("bad field specification");
  300. lu = strtoul(*str, str, 10);
  301. if ((sizeof(long) > sizeof(int) && lu > INT_MAX) || !lu)
  302. bb_error_msg_and_die("bad field specification");
  303. return lu;
  304. }
  305. #endif
  306. int sort_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  307. int sort_main(int argc UNUSED_PARAM, char **argv)
  308. {
  309. char *line, **lines;
  310. char *str_ignored, *str_o, *str_t;
  311. llist_t *lst_k = NULL;
  312. int i, flag;
  313. int linecount;
  314. unsigned opts;
  315. xfunc_error_retval = 2;
  316. /* Parse command line options */
  317. /* -o and -t can be given at most once */
  318. opt_complementary = "o--o:t--t:" /* -t, -o: at most one of each */
  319. "k::"; /* -k takes list */
  320. opts = getopt32(argv, OPT_STR, &str_ignored, &str_ignored, &str_o, &lst_k, &str_t);
  321. /* global b strips leading and trailing spaces */
  322. if (opts & FLAG_b)
  323. option_mask32 |= FLAG_bb;
  324. #if ENABLE_FEATURE_SORT_BIG
  325. if (opts & FLAG_t) {
  326. if (!str_t[0] || str_t[1])
  327. bb_error_msg_and_die("bad -t parameter");
  328. key_separator = str_t[0];
  329. }
  330. /* note: below this point we use option_mask32, not opts,
  331. * since that reduces register pressure and makes code smaller */
  332. /* parse sort key */
  333. while (lst_k) {
  334. enum {
  335. FLAG_allowed_for_k =
  336. FLAG_n | /* Numeric sort */
  337. FLAG_g | /* Sort using strtod() */
  338. FLAG_M | /* Sort date */
  339. FLAG_b | /* Ignore leading blanks */
  340. FLAG_r | /* Reverse */
  341. FLAG_d | /* Ignore !(isalnum()|isspace()) */
  342. FLAG_f | /* Force uppercase */
  343. FLAG_i | /* Ignore !isprint() */
  344. 0
  345. };
  346. struct sort_key *key = add_key();
  347. char *str_k = llist_pop(&lst_k);
  348. i = 0; /* i==0 before comma, 1 after (-k3,6) */
  349. while (*str_k) {
  350. /* Start of range */
  351. /* Cannot use bb_strtou - suffix can be a letter */
  352. key->range[2*i] = str2u(&str_k);
  353. if (*str_k == '.') {
  354. str_k++;
  355. key->range[2*i+1] = str2u(&str_k);
  356. }
  357. while (*str_k) {
  358. const char *temp2;
  359. if (*str_k == ',' && !i++) {
  360. str_k++;
  361. break;
  362. } /* no else needed: fall through to syntax error
  363. because comma isn't in OPT_STR */
  364. temp2 = strchr(OPT_STR, *str_k);
  365. if (!temp2)
  366. bb_error_msg_and_die("unknown key option");
  367. flag = 1 << (temp2 - OPT_STR);
  368. if (flag & ~FLAG_allowed_for_k)
  369. bb_error_msg_and_die("unknown sort type");
  370. /* b after ',' means strip _trailing_ space */
  371. if (i && flag == FLAG_b)
  372. flag = FLAG_bb;
  373. key->flags |= flag;
  374. str_k++;
  375. }
  376. }
  377. }
  378. #endif
  379. /* Open input files and read data */
  380. argv += optind;
  381. if (!*argv)
  382. *--argv = (char*)"-";
  383. linecount = 0;
  384. lines = NULL;
  385. do {
  386. /* coreutils 6.9 compat: abort on first open error,
  387. * do not continue to next file: */
  388. FILE *fp = xfopen_stdin(*argv);
  389. for (;;) {
  390. line = GET_LINE(fp);
  391. if (!line)
  392. break;
  393. lines = xrealloc_vector(lines, 6, linecount);
  394. lines[linecount++] = line;
  395. }
  396. fclose_if_not_stdin(fp);
  397. } while (*++argv);
  398. #if ENABLE_FEATURE_SORT_BIG
  399. /* if no key, perform alphabetic sort */
  400. if (!key_list)
  401. add_key()->range[0] = 1;
  402. /* handle -c */
  403. if (option_mask32 & FLAG_c) {
  404. int j = (option_mask32 & FLAG_u) ? -1 : 0;
  405. for (i = 1; i < linecount; i++) {
  406. if (compare_keys(&lines[i-1], &lines[i]) > j) {
  407. fprintf(stderr, "Check line %u\n", i);
  408. return EXIT_FAILURE;
  409. }
  410. }
  411. return EXIT_SUCCESS;
  412. }
  413. #endif
  414. /* Perform the actual sort */
  415. qsort(lines, linecount, sizeof(lines[0]), compare_keys);
  416. /* handle -u */
  417. if (option_mask32 & FLAG_u) {
  418. flag = 0;
  419. /* coreutils 6.3 drop lines for which only key is the same */
  420. /* -- disabling last-resort compare... */
  421. option_mask32 |= FLAG_s;
  422. for (i = 1; i < linecount; i++) {
  423. if (compare_keys(&lines[flag], &lines[i]) == 0)
  424. free(lines[i]);
  425. else
  426. lines[++flag] = lines[i];
  427. }
  428. if (linecount)
  429. linecount = flag+1;
  430. }
  431. /* Print it */
  432. #if ENABLE_FEATURE_SORT_BIG
  433. /* Open output file _after_ we read all input ones */
  434. if (option_mask32 & FLAG_o)
  435. xmove_fd(xopen(str_o, O_WRONLY|O_CREAT|O_TRUNC), STDOUT_FILENO);
  436. #endif
  437. flag = (option_mask32 & FLAG_z) ? '\0' : '\n';
  438. for (i = 0; i < linecount; i++)
  439. printf("%s%c", lines[i], flag);
  440. fflush_stdout_and_exit(EXIT_SUCCESS);
  441. }