aboutsummaryrefslogtreecommitdiff
path: root/bin/rndl.awk
blob: f495a28c7899f800af3105ae9c08440d2dc079d6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# Print a random line from input

# Process arguments
BEGIN {

    # Name self
    self = "rndl"

    # Seed the random number generator
    "rnds 2>/dev/null" | getline seed
    if (length(seed))
        srand(seed)
    else
        srand()
}

# Iterate over the lines, randomly assigning the first field of each one with a
# decreasing probability
rand() * NR < 1 { ln = $0 }

# Check and print
END {

    # Check that we processed at least one line
    if (!NR) {
        printf "%s: No lines found on input\n", self | "cat >&2"
        exit(1)
    }

    # Print the line
    print ln
}