1 /* vi: set sw=4 ts=4: */
3 * shuf: Write a random permutation of the input lines to standard output.
5 * Copyright (C) 2014 by Bartosz Golaszewski <bartekgola@gmail.com>
7 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
10 //config: bool "shuf (5.4 kb)"
13 //config: Generate random permutations
15 //applet:IF_SHUF(APPLET_NOEXEC(shuf, shuf, BB_DIR_USR_BIN, BB_SUID_DROP, shuf))
17 //kbuild:lib-$(CONFIG_SHUF) += shuf.o
19 //usage:#define shuf_trivial_usage
20 //usage: "[-e|-i L-H] [-n NUM] [-o FILE] [-z] [FILE|ARG...]"
21 //usage:#define shuf_full_usage "\n\n"
22 //usage: "Randomly permute lines\n"
23 //usage: "\n -e Treat ARGs as lines"
24 //usage: "\n -i L-H Treat numbers L-H as lines"
25 //usage: "\n -n NUM Output at most NUM lines"
26 //usage: "\n -o FILE Write to FILE, not standard output"
27 //usage: "\n -z End lines with zero byte, not newline"
31 /* This is a NOEXEC applet. Be very careful! */
33 #define OPT_e (1 << 0)
34 #define OPT_i (1 << 1)
35 #define OPT_n (1 << 2)
36 #define OPT_o (1 << 3)
37 #define OPT_z (1 << 4)
38 #define OPT_STR "ei:n:o:z"
41 * Use the Fisher-Yates shuffle algorithm on an array of lines.
43 static void shuffle_lines(char **lines, unsigned numlines)
49 srand(monotonic_us());
51 for (i = numlines-1; i > 0; i--) {
53 /* RAND_MAX can be as small as 32767 */
63 int shuf_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
64 int shuf_main(int argc, char **argv)
67 char *opt_i_str, *opt_n_str, *opt_o_str;
73 opts = getopt32(argv, "^"
75 "\0" "e--i:i--e"/* mutually exclusive */,
76 &opt_i_str, &opt_n_str, &opt_o_str
82 /* Prepare lines for shuffling - either: */
84 /* make lines from command-line arguments */
89 /* create a range of numbers */
93 dash = strchr(opt_i_str, '-');
95 bb_error_msg_and_die("bad range '%s'", opt_i_str);
98 lo = xatou(opt_i_str);
102 bb_error_msg_and_die("bad range '%s'", opt_i_str);
105 numlines = (hi+1) - lo;
106 lines = xmalloc(numlines * sizeof(lines[0]));
107 for (i = 0; i < numlines; i++) {
108 lines[i] = (char*)(uintptr_t)lo;
112 /* default - read lines from stdin or the input file */
118 fp = xfopen_stdin(argv[0] ? argv[0] : "-");
122 char *line = xmalloc_fgetline(fp);
125 lines = xrealloc_vector(lines, 6, numlines);
126 lines[numlines++] = line;
128 fclose_if_not_stdin(fp);
132 shuffle_lines(lines, numlines);
135 xmove_fd(xopen(opt_o_str, O_WRONLY|O_CREAT|O_TRUNC), STDOUT_FILENO);
139 maxlines = xatou(opt_n_str);
140 if (numlines > maxlines)
148 for (i = 0; i < numlines; i++) {
150 printf("%u%c", (unsigned)(uintptr_t)lines[i], eol);
152 printf("%s%c", lines[i], eol);
155 fflush_stdout_and_exit(EXIT_SUCCESS);