1 /* vi: set sw=4 ts=4: */
3 * SuS3 compliant sort implementation for busybox
5 * Copyright (C) 2004 by Rob Landley <rob@landley.net>
7 * MAINTAINER: Rob Landley <rob@landley.net>
9 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
11 * See SuS3 sort standard at:
12 * http://www.opengroup.org/onlinepubs/007904975/utilities/sort.html
18 //config: sort is used to sort lines of text in specified files.
20 //config:config FEATURE_SORT_BIG
21 //config: bool "Full SuSv3 compliant sort (support -ktcsbdfiozgM)"
23 //config: depends on SORT
25 //config: Without this, sort only supports -r, -u, 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.
29 //config: The SuSv3 sort standard is available at:
30 //config: http://www.opengroup.org/onlinepubs/007904975/utilities/sort.html
32 //applet:IF_SORT(APPLET_NOEXEC(sort, sort, BB_DIR_USR_BIN, BB_SUID_DROP, sort))
34 //kbuild:lib-$(CONFIG_SORT) += sort.o
36 //usage:#define sort_trivial_usage
38 //usage: IF_FEATURE_SORT_BIG("gMcszbdfiokt] [-o FILE] [-k start[.offset][opts][,end[.offset][opts]] [-t CHAR")
39 //usage: "] [FILE]..."
40 //usage:#define sort_full_usage "\n\n"
41 //usage: "Sort lines of text\n"
42 //usage: IF_FEATURE_SORT_BIG(
43 //usage: "\n -o FILE Output to FILE"
44 //usage: "\n -c Check whether input is sorted"
45 //usage: "\n -b Ignore leading blanks"
46 //usage: "\n -f Ignore case"
47 //usage: "\n -i Ignore unprintable characters"
48 //usage: "\n -d Dictionary order (blank or alphanumeric only)"
49 //usage: "\n -g General numerical sort"
50 //usage: "\n -M Sort month"
52 //-h, --human-numeric-sort: compare human readable numbers (e.g., 2K 1G)
53 //usage: "\n -n Sort numbers"
54 //usage: IF_FEATURE_SORT_BIG(
55 //usage: "\n -t CHAR Field separator"
56 //usage: "\n -k N[,M] Sort by Nth field"
58 //usage: "\n -r Reverse sort order"
59 //usage: IF_FEATURE_SORT_BIG(
60 //usage: "\n -s Stable (don't sort ties alphabetically)"
62 //usage: "\n -u Suppress duplicate lines"
63 //usage: IF_FEATURE_SORT_BIG(
64 //usage: "\n -z Lines are terminated by NUL, not newline"
65 ////usage: "\n -m Ignored for GNU compatibility"
66 ////usage: "\n -S BUFSZ Ignored for GNU compatibility"
67 ////usage: "\n -T TMPDIR Ignored for GNU compatibility"
70 //usage:#define sort_example_usage
71 //usage: "$ echo -e \"e\\nf\\nb\\nd\\nc\\na\" | sort\n"
78 //usage: IF_FEATURE_SORT_BIG(
79 //usage: "$ echo -e \"c 3\\nb 2\\nd 2\" | $SORT -k 2,2n -k 1,1r\n"
88 /* This is a NOEXEC applet. Be very careful! */
92 sort [-m][-o output][-bdfinru][-t char][-k keydef]... [file...]
93 sort -c [-bdfinru][-t char][-k keydef][file]
96 /* These are sort types */
97 static const char OPT_STR[] ALIGN1 = "ngMucszbrdfimS:T:o:k:*t:";
99 FLAG_n = 1, /* Numeric sort */
100 FLAG_g = 2, /* Sort using strtod() */
101 FLAG_M = 4, /* Sort date */
102 /* ucsz apply to root level only, not keys. b at root level implies bb */
103 FLAG_u = 8, /* Unique */
104 FLAG_c = 0x10, /* Check: no output, exit(!ordered) */
105 FLAG_s = 0x20, /* Stable sort, no ascii fallback at end */
106 FLAG_z = 0x40, /* Input and output is NUL terminated, not \n */
107 /* These can be applied to search keys, the previous four can't */
108 FLAG_b = 0x80, /* Ignore leading blanks */
109 FLAG_r = 0x100, /* Reverse */
110 FLAG_d = 0x200, /* Ignore !(isalnum()|isspace()) */
111 FLAG_f = 0x400, /* Force uppercase */
112 FLAG_i = 0x800, /* Ignore !isprint() */
113 FLAG_m = 0x1000, /* ignored: merge already sorted files; do not sort */
114 FLAG_S = 0x2000, /* ignored: -S, --buffer-size=SIZE */
115 FLAG_T = 0x4000, /* ignored: -T, --temporary-directory=DIR */
119 FLAG_bb = 0x80000000, /* Ignore trailing blanks */
122 #if ENABLE_FEATURE_SORT_BIG
123 static char key_separator;
125 static struct sort_key {
126 struct sort_key *next_key; /* linked list */
127 unsigned range[4]; /* start word, start char, end word, end char */
131 static char *get_key(char *str, struct sort_key *key, int flags)
133 int start = start; /* for compiler */
138 /* Special case whole string, so we don't have to make a copy */
139 if (key->range[0] == 1 && !key->range[1] && !key->range[2] && !key->range[3]
140 && !(flags & (FLAG_b | FLAG_d | FLAG_f | FLAG_i | FLAG_bb))
145 /* Find start of key on first pass, end on second pass */
147 for (j = 0; j < 2; j++) {
148 if (!key->range[2*j])
150 /* Loop through fields */
152 unsigned char ch = 0;
155 for (i = 1; i < key->range[2*j] + j; i++) {
157 /* Skip body of key and separator */
158 while ((ch = str[end]) != '\0') {
160 if (ch == key_separator)
164 /* Skip leading blanks */
165 while (isspace(str[end]))
167 /* Skip body of key */
168 while (str[end] != '\0') {
169 if (isspace(str[end]))
175 /* Remove last delim: "abc:def:" => "abc:def" */
177 //if (str[end-1] != key_separator)
178 // bb_error_msg(_and_die("BUG! "
179 // "str[start:%d,end:%d]:'%.*s'",
180 // start, end, (int)(end-start), &str[start]);
186 /* Strip leading whitespace if necessary */
188 /* not using skip_whitespace() for speed */
189 while (isspace(str[start])) start++;
190 /* Strip trailing whitespace if necessary */
192 while (end > start && isspace(str[end-1])) end--;
193 /* -kSTART,N.ENDCHAR: honor ENDCHAR (1-based) */
196 if (end > len) end = len;
198 /* -kN.STARTCHAR[,...]: honor STARTCHAR (1-based) */
200 start += key->range[1] - 1;
201 if (start > len) start = len;
206 str = xstrndup(str+start, end-start);
208 if (flags & FLAG_d) {
209 for (start = end = 0; str[end]; end++)
210 if (isspace(str[end]) || isalnum(str[end]))
211 str[start++] = str[end];
215 if (flags & FLAG_i) {
216 for (start = end = 0; str[end]; end++)
217 if (isprint_asciionly(str[end]))
218 str[start++] = str[end];
223 for (i = 0; str[i]; i++)
224 str[i] = toupper(str[i]);
229 static struct sort_key *add_key(void)
231 struct sort_key **pkey = &key_list;
233 pkey = &((*pkey)->next_key);
234 return *pkey = xzalloc(sizeof(struct sort_key));
237 #define GET_LINE(fp) \
238 ((option_mask32 & FLAG_z) \
239 ? bb_get_chunk_from_file(fp, NULL) \
240 : xmalloc_fgetline(fp))
242 #define GET_LINE(fp) xmalloc_fgetline(fp)
245 /* Iterate through keys list and perform comparisons */
246 static int compare_keys(const void *xarg, const void *yarg)
248 int flags = option_mask32, retval = 0;
251 #if ENABLE_FEATURE_SORT_BIG
252 struct sort_key *key;
254 for (key = key_list; !retval && key; key = key->next_key) {
255 flags = key->flags ? key->flags : option_mask32;
256 /* Chop out and modify key chunks, handling -dfib */
257 x = get_key(*(char **)xarg, key, flags);
258 y = get_key(*(char **)yarg, key, flags);
260 /* This curly bracket serves no purpose but to match the nesting
261 * level of the for () loop we're not using */
266 /* Perform actual comparison */
267 switch (flags & (FLAG_n | FLAG_M | FLAG_g)) {
269 bb_error_msg_and_die("unknown sort type");
273 #if ENABLE_LOCALE_SUPPORT
274 retval = strcoll(x, y);
276 retval = strcmp(x, y);
279 #if ENABLE_FEATURE_SORT_BIG
282 double dx = strtod(x, &xx);
283 double dy = strtod(y, &yy);
284 /* not numbers < NaN < -infinity < numbers < +infinity) */
286 retval = (y == yy ? 0 : -1);
289 /* Check for isnan */
291 retval = (dy != dy) ? 0 : -1;
294 /* Check for infinity. Could underflow, but it avoids libm. */
295 else if (1.0 / dx == 0.0) {
297 retval = (1.0 / dy == 0.0 && dy < 0) ? 0 : -1;
299 retval = (1.0 / dy == 0.0 && dy > 0) ? 0 : 1;
300 } else if (1.0 / dy == 0.0)
301 retval = (dy < 0) ? 1 : -1;
303 retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
311 xx = strptime(x, "%b", &thyme);
313 yy = strptime(y, "%b", &thyme);
315 retval = (!yy) ? 0 : -1;
319 retval = dx - thyme.tm_mon;
322 /* Full floating point version of -n */
326 retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
330 /* Free key copies. */
331 if (x != *(char **)xarg) free(x);
332 if (y != *(char **)yarg) free(y);
333 /* if (retval) break; - done by for () anyway */
335 /* Integer version of -n for tiny systems */
337 retval = atoi(x) - atoi(y);
343 /* Perform fallback sort if necessary */
344 if (!retval && !(option_mask32 & FLAG_s)) {
345 flags = option_mask32;
346 retval = strcmp(*(char **)xarg, *(char **)yarg);
355 #if ENABLE_FEATURE_SORT_BIG
356 static unsigned str2u(char **str)
359 if (!isdigit((*str)[0]))
360 bb_error_msg_and_die("bad field specification");
361 lu = strtoul(*str, str, 10);
362 if ((sizeof(long) > sizeof(int) && lu > INT_MAX) || !lu)
363 bb_error_msg_and_die("bad field specification");
368 int sort_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
369 int sort_main(int argc UNUSED_PARAM, char **argv)
372 char *str_ignored, *str_o, *str_t;
373 llist_t *lst_k = NULL;
378 xfunc_error_retval = 2;
380 /* Parse command line options */
381 /* -o and -t can be given at most once */
382 opt_complementary = "o--o:t--t"; /* -t, -o: at most one of each */
383 opts = getopt32(argv, OPT_STR, &str_ignored, &str_ignored, &str_o, &lst_k, &str_t);
384 /* global b strips leading and trailing spaces */
386 option_mask32 |= FLAG_bb;
387 #if ENABLE_FEATURE_SORT_BIG
389 if (!str_t[0] || str_t[1])
390 bb_error_msg_and_die("bad -t parameter");
391 key_separator = str_t[0];
393 /* note: below this point we use option_mask32, not opts,
394 * since that reduces register pressure and makes code smaller */
400 FLAG_n | /* Numeric sort */
401 FLAG_g | /* Sort using strtod() */
402 FLAG_M | /* Sort date */
403 FLAG_b | /* Ignore leading blanks */
404 FLAG_r | /* Reverse */
405 FLAG_d | /* Ignore !(isalnum()|isspace()) */
406 FLAG_f | /* Force uppercase */
407 FLAG_i | /* Ignore !isprint() */
410 struct sort_key *key = add_key();
411 char *str_k = llist_pop(&lst_k);
413 i = 0; /* i==0 before comma, 1 after (-k3,6) */
416 /* Cannot use bb_strtou - suffix can be a letter */
417 key->range[2*i] = str2u(&str_k);
420 key->range[2*i+1] = str2u(&str_k);
426 if (*str_k == ',' && !i++) {
429 } /* no else needed: fall through to syntax error
430 because comma isn't in OPT_STR */
431 idx = strchr(OPT_STR, *str_k);
433 bb_error_msg_and_die("unknown key option");
434 flag = 1 << (idx - OPT_STR);
435 if (flag & ~FLAG_allowed_for_k)
436 bb_error_msg_and_die("unknown sort type");
437 /* b after ',' means strip _trailing_ space */
438 if (i && flag == FLAG_b)
447 /* Open input files and read data */
450 *--argv = (char*)"-";
454 /* coreutils 6.9 compat: abort on first open error,
455 * do not continue to next file: */
456 FILE *fp = xfopen_stdin(*argv);
461 lines = xrealloc_vector(lines, 6, linecount);
462 lines[linecount++] = line;
464 fclose_if_not_stdin(fp);
467 #if ENABLE_FEATURE_SORT_BIG
468 /* If no key, perform alphabetic sort */
470 add_key()->range[0] = 1;
472 if (option_mask32 & FLAG_c) {
473 int j = (option_mask32 & FLAG_u) ? -1 : 0;
474 for (i = 1; i < linecount; i++) {
475 if (compare_keys(&lines[i-1], &lines[i]) > j) {
476 fprintf(stderr, "Check line %u\n", i);
483 /* Perform the actual sort */
484 qsort(lines, linecount, sizeof(lines[0]), compare_keys);
487 if (option_mask32 & FLAG_u) {
489 /* coreutils 6.3 drop lines for which only key is the same */
490 /* -- disabling last-resort compare... */
491 option_mask32 |= FLAG_s;
492 for (i = 1; i < linecount; i++) {
493 if (compare_keys(&lines[j], &lines[i]) == 0)
496 lines[++j] = lines[i];
503 #if ENABLE_FEATURE_SORT_BIG
504 /* Open output file _after_ we read all input ones */
505 if (option_mask32 & FLAG_o)
506 xmove_fd(xopen(str_o, O_WRONLY|O_CREAT|O_TRUNC), STDOUT_FILENO);
509 int ch = (option_mask32 & FLAG_z) ? '\0' : '\n';
510 for (i = 0; i < linecount; i++)
511 printf("%s%c", lines[i], ch);
514 fflush_stdout_and_exit(EXIT_SUCCESS);