Amin Shah Gilani
Amin Shah Gilani

Reputation: 9886

How do I shuffle a file in one-line ruby -e

I have the following file:

A
B
C
...

I want ruby -e to read the file, shuffle it, and standard output it, like so for example:

P
C
A
...

How do I do this. So far, I've gotten to ruby -e 'puts $_' filename.txt.

Upvotes: 2

Views: 179

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110745

Create a test file:

str = "three\nblind\nmice\n"
File.write('data_in', str)
  #= 17

From the command line.

If not limited to Ruby1:

cat data_in|shuf
mice
three
blind

Using Ruby,

ruby -e "puts STDIN.readlines.shuffle.join" < data_in
mice
blind
three

or

ruby -e "puts ARGF.readlines.shuffle.join" data_in
blind
mice
three

1 See doc. This doesn't work with OS X, but there's a fix.

Upvotes: 1

Ry-
Ry-

Reputation: 225164

You can read all lines from ARGF into an array:

ruby -e 'puts $<.to_a.shuffle' filename.txt

or by splatting the lines to make it extra short:

ruby -e'puts [*$<].shuffle' filename.txt

It’ll also accept input on stdin with no filename.

Upvotes: 6

Amin Shah Gilani
Amin Shah Gilani

Reputation: 9886

ruby -ne 'BEGIN { data = [] }; data << $_; END {puts data.shuffle}' filename.txt

This does the following:

  • Add the -n flag, which wraps the input in while gets(); ... end;
  • Use BEGIN to create an initial data variable that's shared across every loop run
  • Shovels the data into the data variable on every loop
  • Use END to output that final data variable.

Upvotes: 0

Related Questions