Shuffle or pick random lines from a file

November 13, 2017

There comes a day in the life a developer when one needs to choose random lines from a text file. This is useful for a myriad of reasons, like taking a random sample of a CSV file, or shuffling the code of your coworkers, just for fun.

There are multiple tools in the UNIX toolbox to solve this problem, but the shuf utility is by far the most elegant:

# shuffles a file and prints to stdout
shuf file

# pick 100 random lines from a file
shuf file -n 100

There’s also sort which has a --random-sort flag.

OSX

If run OS X, though, you might be surprised that there’s no shuf tool and that sort does not really have a random-sort flag. Fortunately, there’s brew:

brew install coreutils

Now you can use either gshuf or gsort!

© 2017 | Powered by Hugo