Reputation: 9886
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
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
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
Reputation: 9886
ruby -ne 'BEGIN { data = [] }; data << $_; END {puts data.shuffle}' filename.txt
This does the following:
-n
flag, which wraps the input in while gets(); ... end;
BEGIN
to create an initial data
variable that's shared across every loop rundata
variable on every loopEND
to output that final data
variable.Upvotes: 0