sort.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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 -ktcbdfiogM)"
  22. //config: default y
  23. //config: depends on SORT
  24. //config: help
  25. //config: Without this, sort only supports -rusz, 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. //config:
  32. //config:config FEATURE_SORT_OPTIMIZE_MEMORY
  33. //config: bool "Use less memory (but might be slower)"
  34. //config: default n # defaults to N since we are size-paranoid tribe
  35. //config: depends on SORT
  36. //config: help
  37. //config: Attempt to use less memory (by storing only one copy
  38. //config: of duplicated lines, and such). Useful if you work on huge files.
  39. //applet:IF_SORT(APPLET_NOEXEC(sort, sort, BB_DIR_USR_BIN, BB_SUID_DROP, sort))
  40. //kbuild:lib-$(CONFIG_SORT) += sort.o
  41. //usage:#define sort_trivial_usage
  42. //usage: "[-nru"
  43. //usage: IF_FEATURE_SORT_BIG("gMcszbdfiokt] [-o FILE] [-k start[.offset][opts][,end[.offset][opts]] [-t CHAR")
  44. //usage: "] [FILE]..."
  45. //usage:#define sort_full_usage "\n\n"
  46. //usage: "Sort lines of text\n"
  47. //usage: IF_FEATURE_SORT_BIG(
  48. //usage: "\n -o FILE Output to FILE"
  49. //usage: "\n -c Check whether input is sorted"
  50. //usage: "\n -b Ignore leading blanks"
  51. //usage: "\n -f Ignore case"
  52. //usage: "\n -i Ignore unprintable characters"
  53. //usage: "\n -d Dictionary order (blank or alphanumeric only)"
  54. //usage: )
  55. //-h, --human-numeric-sort: compare human readable numbers (e.g., 2K 1G)
  56. //usage: "\n -n Sort numbers"
  57. //usage: IF_FEATURE_SORT_BIG(
  58. //usage: "\n -g General numerical sort"
  59. //usage: "\n -M Sort month"
  60. //usage: "\n -t CHAR Field separator"
  61. //usage: "\n -k N[,M] Sort by Nth field"
  62. //usage: )
  63. //usage: "\n -r Reverse sort order"
  64. //usage: "\n -s Stable (don't sort ties alphabetically)"
  65. //usage: "\n -u Suppress duplicate lines"
  66. //usage: "\n -z Lines are terminated by NUL, not newline"
  67. ///////: "\n -m Ignored for GNU compatibility"
  68. ///////: "\n -S BUFSZ Ignored for GNU compatibility"
  69. ///////: "\n -T TMPDIR Ignored for GNU compatibility"
  70. //usage:
  71. //usage:#define sort_example_usage
  72. //usage: "$ echo -e \"e\\nf\\nb\\nd\\nc\\na\" | sort\n"
  73. //usage: "a\n"
  74. //usage: "b\n"
  75. //usage: "c\n"
  76. //usage: "d\n"
  77. //usage: "e\n"
  78. //usage: "f\n"
  79. //usage: IF_FEATURE_SORT_BIG(
  80. //usage: "$ echo -e \"c 3\\nb 2\\nd 2\" | $SORT -k 2,2n -k 1,1r\n"
  81. //usage: "d 2\n"
  82. //usage: "b 2\n"
  83. //usage: "c 3\n"
  84. //usage: )
  85. //usage: ""
  86. #include "libbb.h"
  87. /* These are sort types */
  88. enum {
  89. FLAG_n = 1, /* Numeric sort */
  90. FLAG_g = 2, /* Sort using strtod() */
  91. FLAG_M = 4, /* Sort date */
  92. /* ucsz apply to root level only, not keys. b at root level implies bb */
  93. FLAG_u = 8, /* Unique */
  94. FLAG_c = 0x10, /* Check: no output, exit(!ordered) */
  95. FLAG_s = 0x20, /* Stable sort, no ascii fallback at end */
  96. FLAG_z = 0x40, /* Input and output is NUL terminated, not \n */
  97. /* These can be applied to search keys, the previous four can't */
  98. FLAG_b = 0x80, /* Ignore leading blanks */
  99. FLAG_r = 0x100, /* Reverse */
  100. FLAG_d = 0x200, /* Ignore !(isalnum()|isspace()) */
  101. FLAG_f = 0x400, /* Force uppercase */
  102. FLAG_i = 0x800, /* Ignore !isprint() */
  103. FLAG_m = 0x1000, /* ignored: merge already sorted files; do not sort */
  104. FLAG_S = 0x2000, /* ignored: -S, --buffer-size=SIZE */
  105. FLAG_T = 0x4000, /* ignored: -T, --temporary-directory=DIR */
  106. FLAG_o = 0x8000,
  107. FLAG_k = 0x10000,
  108. FLAG_t = 0x20000,
  109. FLAG_bb = 0x80000000, /* Ignore trailing blanks */
  110. FLAG_no_tie_break = 0x40000000,
  111. };
  112. static const char sort_opt_str[] ALIGN1 = "^"
  113. "ngMucszbrdfimS:T:o:k:*t:"
  114. "\0" "o--o:t--t"/*-t, -o: at most one of each*/;
  115. /*
  116. * OPT_STR must not be string literal, needs to have stable address:
  117. * code uses "strchr(OPT_STR,c) - OPT_STR" idiom.
  118. */
  119. #define OPT_STR (sort_opt_str + 1)
  120. #if ENABLE_FEATURE_SORT_BIG
  121. static char key_separator;
  122. static struct sort_key {
  123. struct sort_key *next_key; /* linked list */
  124. unsigned range[4]; /* start word, start char, end word, end char */
  125. unsigned flags;
  126. } *key_list;
  127. /* This is a NOEXEC applet. Be very careful! */
  128. static char *get_key(char *str, struct sort_key *key, int flags)
  129. {
  130. int start = start; /* for compiler */
  131. int end;
  132. int len, j;
  133. unsigned i;
  134. /* Special case whole string, so we don't have to make a copy */
  135. if (key->range[0] == 1 && !key->range[1] && !key->range[2] && !key->range[3]
  136. && !(flags & (FLAG_b | FLAG_d | FLAG_f | FLAG_i | FLAG_bb))
  137. ) {
  138. return str;
  139. }
  140. /* Find start of key on first pass, end on second pass */
  141. len = strlen(str);
  142. for (j = 0; j < 2; j++) {
  143. if (!key->range[2*j])
  144. end = len;
  145. /* Loop through fields */
  146. else {
  147. unsigned char ch = 0;
  148. end = 0;
  149. for (i = 1; i < key->range[2*j] + j; i++) {
  150. if (key_separator) {
  151. /* Skip body of key and separator */
  152. while ((ch = str[end]) != '\0') {
  153. end++;
  154. if (ch == key_separator)
  155. break;
  156. }
  157. } else {
  158. /* Skip leading blanks */
  159. while (isspace(str[end]))
  160. end++;
  161. /* Skip body of key */
  162. while (str[end] != '\0') {
  163. if (isspace(str[end]))
  164. break;
  165. end++;
  166. }
  167. }
  168. }
  169. /* Remove last delim: "abc:def:" => "abc:def" */
  170. if (j && ch) {
  171. //if (str[end-1] != key_separator)
  172. // bb_error_msg(_and_die("BUG! "
  173. // "str[start:%d,end:%d]:'%.*s'",
  174. // start, end, (int)(end-start), &str[start]);
  175. end--;
  176. }
  177. }
  178. if (!j) start = end;
  179. }
  180. /* Strip leading whitespace if necessary */
  181. if (flags & FLAG_b)
  182. /* not using skip_whitespace() for speed */
  183. while (isspace(str[start])) start++;
  184. /* Strip trailing whitespace if necessary */
  185. if (flags & FLAG_bb)
  186. while (end > start && isspace(str[end-1])) end--;
  187. /* -kSTART,N.ENDCHAR: honor ENDCHAR (1-based) */
  188. if (key->range[3]) {
  189. end = key->range[3];
  190. if (end > len) end = len;
  191. }
  192. /* -kN.STARTCHAR[,...]: honor STARTCHAR (1-based) */
  193. if (key->range[1]) {
  194. start += key->range[1] - 1;
  195. if (start > len) start = len;
  196. }
  197. /* Make the copy */
  198. if (end < start)
  199. end = start;
  200. str = xstrndup(str+start, end-start);
  201. /* Handle -d */
  202. if (flags & FLAG_d) {
  203. for (start = end = 0; str[end]; end++)
  204. if (isspace(str[end]) || isalnum(str[end]))
  205. str[start++] = str[end];
  206. str[start] = '\0';
  207. }
  208. /* Handle -i */
  209. if (flags & FLAG_i) {
  210. for (start = end = 0; str[end]; end++)
  211. if (isprint_asciionly(str[end]))
  212. str[start++] = str[end];
  213. str[start] = '\0';
  214. }
  215. /* Handle -f */
  216. if (flags & FLAG_f)
  217. for (i = 0; str[i]; i++)
  218. str[i] = toupper(str[i]);
  219. return str;
  220. }
  221. static struct sort_key *add_key(void)
  222. {
  223. struct sort_key **pkey = &key_list;
  224. while (*pkey)
  225. pkey = &((*pkey)->next_key);
  226. return *pkey = xzalloc(sizeof(struct sort_key));
  227. }
  228. #define GET_LINE(fp) \
  229. ((option_mask32 & FLAG_z) \
  230. ? bb_get_chunk_from_file(fp, NULL) \
  231. : xmalloc_fgetline(fp))
  232. #else
  233. #define GET_LINE(fp) xmalloc_fgetline(fp)
  234. #endif
  235. /* Iterate through keys list and perform comparisons */
  236. static int compare_keys(const void *xarg, const void *yarg)
  237. {
  238. int flags = option_mask32, retval = 0;
  239. char *x, *y;
  240. #if ENABLE_FEATURE_SORT_BIG
  241. struct sort_key *key;
  242. for (key = key_list; !retval && key; key = key->next_key) {
  243. flags = key->flags ? key->flags : option_mask32;
  244. /* Chop out and modify key chunks, handling -dfib */
  245. x = get_key(*(char **)xarg, key, flags);
  246. y = get_key(*(char **)yarg, key, flags);
  247. #else
  248. /* This curly bracket serves no purpose but to match the nesting
  249. * level of the for () loop we're not using */
  250. {
  251. x = *(char **)xarg;
  252. y = *(char **)yarg;
  253. #endif
  254. /* Perform actual comparison */
  255. switch (flags & (FLAG_n | FLAG_M | FLAG_g)) {
  256. default:
  257. bb_error_msg_and_die("unknown sort type");
  258. break;
  259. /* Ascii sort */
  260. case 0:
  261. #if ENABLE_LOCALE_SUPPORT
  262. retval = strcoll(x, y);
  263. #else
  264. retval = strcmp(x, y);
  265. #endif
  266. break;
  267. #if ENABLE_FEATURE_SORT_BIG
  268. case FLAG_g: {
  269. char *xx, *yy;
  270. double dx = strtod(x, &xx);
  271. double dy = strtod(y, &yy);
  272. /* not numbers < NaN < -infinity < numbers < +infinity) */
  273. if (x == xx)
  274. retval = (y == yy ? 0 : -1);
  275. else if (y == yy)
  276. retval = 1;
  277. /* Check for isnan */
  278. else if (dx != dx)
  279. retval = (dy != dy) ? 0 : -1;
  280. else if (dy != dy)
  281. retval = 1;
  282. /* Check for infinity. Could underflow, but it avoids libm. */
  283. else if (1.0 / dx == 0.0) {
  284. if (dx < 0)
  285. retval = (1.0 / dy == 0.0 && dy < 0) ? 0 : -1;
  286. else
  287. retval = (1.0 / dy == 0.0 && dy > 0) ? 0 : 1;
  288. } else if (1.0 / dy == 0.0)
  289. retval = (dy < 0) ? 1 : -1;
  290. else
  291. retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
  292. break;
  293. }
  294. case FLAG_M: {
  295. struct tm thyme;
  296. int dx;
  297. char *xx, *yy;
  298. xx = strptime(x, "%b", &thyme);
  299. dx = thyme.tm_mon;
  300. yy = strptime(y, "%b", &thyme);
  301. if (!xx)
  302. retval = (!yy) ? 0 : -1;
  303. else if (!yy)
  304. retval = 1;
  305. else
  306. retval = dx - thyme.tm_mon;
  307. break;
  308. }
  309. /* Full floating point version of -n */
  310. case FLAG_n: {
  311. double dx = atof(x);
  312. double dy = atof(y);
  313. retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
  314. break;
  315. }
  316. } /* switch */
  317. /* Free key copies. */
  318. if (x != *(char **)xarg) free(x);
  319. if (y != *(char **)yarg) free(y);
  320. /* if (retval) break; - done by for () anyway */
  321. #else
  322. /* Integer version of -n for tiny systems */
  323. case FLAG_n:
  324. retval = atoi(x) - atoi(y);
  325. break;
  326. } /* switch */
  327. #endif
  328. } /* for */
  329. if (retval == 0) {
  330. /* So far lines are "the same" */
  331. if (option_mask32 & FLAG_s) {
  332. /* "Stable sort": later line is "greater than",
  333. * IOW: do not allow qsort() to swap equal lines.
  334. */
  335. uint32_t *p32;
  336. uint32_t x32, y32;
  337. char *line;
  338. unsigned len;
  339. line = *(char**)xarg;
  340. len = (strlen(line) + 4) & (~3u);
  341. p32 = (void*)(line + len);
  342. x32 = *p32;
  343. line = *(char**)yarg;
  344. len = (strlen(line) + 4) & (~3u);
  345. p32 = (void*)(line + len);
  346. y32 = *p32;
  347. /* If x > y, 1, else -1 */
  348. retval = (x32 > y32) * 2 - 1;
  349. } else
  350. if (!(option_mask32 & FLAG_no_tie_break)) {
  351. /* fallback sort */
  352. flags = option_mask32;
  353. retval = strcmp(*(char **)xarg, *(char **)yarg);
  354. }
  355. }
  356. if (flags & FLAG_r)
  357. return -retval;
  358. return retval;
  359. }
  360. #if ENABLE_FEATURE_SORT_BIG
  361. static unsigned str2u(char **str)
  362. {
  363. unsigned long lu;
  364. if (!isdigit((*str)[0]))
  365. bb_error_msg_and_die("bad field specification");
  366. lu = strtoul(*str, str, 10);
  367. if ((sizeof(long) > sizeof(int) && lu > INT_MAX) || !lu)
  368. bb_error_msg_and_die("bad field specification");
  369. return lu;
  370. }
  371. #endif
  372. int sort_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  373. int sort_main(int argc UNUSED_PARAM, char **argv)
  374. {
  375. char **lines;
  376. char *str_ignored, *str_o, *str_t;
  377. llist_t *lst_k = NULL;
  378. int i;
  379. int linecount;
  380. unsigned opts;
  381. #if ENABLE_FEATURE_SORT_OPTIMIZE_MEMORY
  382. bool can_drop_dups;
  383. size_t prev_len = 0;
  384. char *prev_line = (char*) "";
  385. /* Postpone optimizing if the input is small, < 16k lines:
  386. * even just free()ing duplicate lines takes time.
  387. */
  388. size_t count_to_optimize_dups = 0x3fff;
  389. #endif
  390. xfunc_error_retval = 2;
  391. /* Parse command line options */
  392. opts = getopt32(argv,
  393. sort_opt_str,
  394. &str_ignored, &str_ignored, &str_o, &lst_k, &str_t
  395. );
  396. #if ENABLE_FEATURE_SORT_OPTIMIZE_MEMORY
  397. /* Can drop dups only if -u but no "complicating" options,
  398. * IOW: if we do a full line compares. Safe options:
  399. * -o FILE Output to FILE
  400. * -z Lines are terminated by NUL, not newline
  401. * -r Reverse sort order
  402. * -s Stable (don't sort ties alphabetically)
  403. * Not sure about these:
  404. * -b Ignore leading blanks
  405. * -f Ignore case
  406. * -i Ignore unprintable characters
  407. * -d Dictionary order (blank or alphanumeric only)
  408. * -n Sort numbers
  409. * -g General numerical sort
  410. * -M Sort month
  411. */
  412. can_drop_dups = ((opts & ~(FLAG_o|FLAG_z|FLAG_r|FLAG_s)) == FLAG_u);
  413. /* Stable sort needs every line to be uniquely allocated,
  414. * disable optimization to reuse strings:
  415. */
  416. if (opts & FLAG_s)
  417. count_to_optimize_dups = (size_t)-1L;
  418. #endif
  419. /* global b strips leading and trailing spaces */
  420. if (opts & FLAG_b)
  421. option_mask32 |= FLAG_bb;
  422. #if ENABLE_FEATURE_SORT_BIG
  423. if (opts & FLAG_t) {
  424. if (!str_t[0] || str_t[1])
  425. bb_error_msg_and_die("bad -t parameter");
  426. key_separator = str_t[0];
  427. }
  428. /* note: below this point we use option_mask32, not opts,
  429. * since that reduces register pressure and makes code smaller */
  430. /* Parse sort key */
  431. while (lst_k) {
  432. enum {
  433. FLAG_allowed_for_k =
  434. FLAG_n | /* Numeric sort */
  435. FLAG_g | /* Sort using strtod() */
  436. FLAG_M | /* Sort date */
  437. FLAG_b | /* Ignore leading blanks */
  438. FLAG_r | /* Reverse */
  439. FLAG_d | /* Ignore !(isalnum()|isspace()) */
  440. FLAG_f | /* Force uppercase */
  441. FLAG_i | /* Ignore !isprint() */
  442. 0
  443. };
  444. struct sort_key *key = add_key();
  445. char *str_k = llist_pop(&lst_k);
  446. i = 0; /* i==0 before comma, 1 after (-k3,6) */
  447. while (*str_k) {
  448. /* Start of range */
  449. /* Cannot use bb_strtou - suffix can be a letter */
  450. key->range[2*i] = str2u(&str_k);
  451. if (*str_k == '.') {
  452. str_k++;
  453. key->range[2*i+1] = str2u(&str_k);
  454. }
  455. while (*str_k) {
  456. int flag;
  457. const char *idx;
  458. if (*str_k == ',' && !i++) {
  459. str_k++;
  460. break;
  461. } /* no else needed: fall through to syntax error
  462. because comma isn't in OPT_STR */
  463. idx = strchr(OPT_STR, *str_k);
  464. if (!idx)
  465. bb_error_msg_and_die("unknown key option");
  466. flag = 1 << (idx - OPT_STR);
  467. if (flag & ~FLAG_allowed_for_k)
  468. bb_error_msg_and_die("unknown sort type");
  469. /* b after ',' means strip _trailing_ space */
  470. if (i && flag == FLAG_b)
  471. flag = FLAG_bb;
  472. key->flags |= flag;
  473. str_k++;
  474. }
  475. }
  476. }
  477. #endif
  478. /* Open input files and read data */
  479. argv += optind;
  480. if (!*argv)
  481. *--argv = (char*)"-";
  482. linecount = 0;
  483. lines = NULL;
  484. do {
  485. /* coreutils 6.9 compat: abort on first open error,
  486. * do not continue to next file: */
  487. FILE *fp = xfopen_stdin(*argv);
  488. for (;;) {
  489. char *line = GET_LINE(fp);
  490. if (!line)
  491. break;
  492. #if ENABLE_FEATURE_SORT_OPTIMIZE_MEMORY
  493. if (count_to_optimize_dups != 0)
  494. count_to_optimize_dups--;
  495. if (count_to_optimize_dups == 0) {
  496. size_t len;
  497. char *new_line;
  498. /* On kernel/linux/arch/ *.[ch] files,
  499. * this reduces memory usage by 6%.
  500. * yes | head -99999999 | sort
  501. * goes down from 1900Mb to 380 Mb.
  502. */
  503. len = strlen(line);
  504. if (len <= prev_len) {
  505. new_line = prev_line + (prev_len - len);
  506. if (strcmp(line, new_line) == 0) {
  507. /* it's a tail of the prev line */
  508. if (can_drop_dups && prev_len == len) {
  509. /* it's identical to prev line */
  510. free(line);
  511. continue;
  512. }
  513. free(line);
  514. line = new_line;
  515. /* continue using longer prev_line
  516. * for future tail tests.
  517. */
  518. goto skip;
  519. }
  520. }
  521. prev_len = len;
  522. prev_line = line;
  523. skip: ;
  524. }
  525. #else
  526. //TODO: lighter version which only drops total dups if can_drop_dups == true
  527. #endif
  528. lines = xrealloc_vector(lines, 6, linecount);
  529. lines[linecount++] = line;
  530. }
  531. fclose_if_not_stdin(fp);
  532. } while (*++argv);
  533. #if ENABLE_FEATURE_SORT_BIG
  534. /* If no key, perform alphabetic sort */
  535. if (!key_list)
  536. add_key()->range[0] = 1;
  537. /* Handle -c */
  538. if (option_mask32 & FLAG_c) {
  539. int j = (option_mask32 & FLAG_u) ? -1 : 0;
  540. for (i = 1; i < linecount; i++) {
  541. if (compare_keys(&lines[i-1], &lines[i]) > j) {
  542. fprintf(stderr, "Check line %u\n", i);
  543. return EXIT_FAILURE;
  544. }
  545. }
  546. return EXIT_SUCCESS;
  547. }
  548. #endif
  549. /* For stable sort, store original line position beyond terminating NUL */
  550. if (option_mask32 & FLAG_s) {
  551. for (i = 0; i < linecount; i++) {
  552. uint32_t *p32;
  553. char *line;
  554. unsigned len;
  555. line = lines[i];
  556. len = (strlen(line) + 4) & (~3u);
  557. lines[i] = line = xrealloc(line, len + 4);
  558. p32 = (void*)(line + len);
  559. *p32 = i;
  560. }
  561. /*option_mask32 |= FLAG_no_tie_break;*/
  562. /* ^^^redundant: if FLAG_s, compare_keys() does no tie break */
  563. }
  564. /* Perform the actual sort */
  565. qsort(lines, linecount, sizeof(lines[0]), compare_keys);
  566. /* Handle -u */
  567. if (option_mask32 & FLAG_u) {
  568. int j = 0;
  569. /* coreutils 6.3 drop lines for which only key is the same
  570. * -- disabling last-resort compare, or else compare_keys()
  571. * will be the same only for completely identical lines.
  572. */
  573. option_mask32 |= FLAG_no_tie_break;
  574. for (i = 1; i < linecount; i++) {
  575. if (compare_keys(&lines[j], &lines[i]) == 0)
  576. free(lines[i]);
  577. else
  578. lines[++j] = lines[i];
  579. }
  580. if (linecount)
  581. linecount = j+1;
  582. }
  583. /* Print it */
  584. #if ENABLE_FEATURE_SORT_BIG
  585. /* Open output file _after_ we read all input ones */
  586. if (option_mask32 & FLAG_o)
  587. xmove_fd(xopen(str_o, O_WRONLY|O_CREAT|O_TRUNC), STDOUT_FILENO);
  588. #endif
  589. {
  590. int ch = (option_mask32 & FLAG_z) ? '\0' : '\n';
  591. for (i = 0; i < linecount; i++)
  592. printf("%s%c", lines[i], ch);
  593. }
  594. fflush_stdout_and_exit(EXIT_SUCCESS);
  595. }