Shuffled standard input or shuffled files

by Carson Reynolds

Every now and then I like to shuffle a file or a directory. Here is a trivial shuffle script in Ruby:

#!/usr/bin/ruby

# output randomly shuffled lines from the file passed as an argument
# or input fed to standard input
# ex: ls | shuffle.rb 
# This produces a randomly shuffled directory

# a modified version of the code from http://bit.ly/dUdAb9
# shuffle modified from "Programming in Ruby" by Thomas and Hunt

# get the lines:
if ARGV.size == 1
  lines = IO.readlines(ARGV[0])
elsif not ARGF.eof?
  lines = ARGF.readlines
else
  abort "usage: shuffle.rb <file>"
end

# pick a random line, remove it, and print it
lines.size.times do
  print lines.delete_at(rand(lines.size))
end
Advertisements