What's an easy way to read random line from a file in Unix command line?
相关问题
- Is shmid returned by shmget() unique across proces
- how to get running process information in java?
- Unity - Get Random Color at Spawning
- Error building gcc 4.8.3 from source: libstdc++.so
- Why should we check WIFEXITED after wait in order
Another alternative:
using a bash script:
A solution that also works on MacOSX, and should also works on Linux(?):
Where:
N
is the number of random lines you wantNR==FNR {lineN[$1]; next}(FNR in lineN) file1 file2
--> save line numbers written infile1
and then print corresponding line infile2
jot -r $N 1 $(wc -l < $file)
--> drawN
numbers randomly (-r
) in range(1, number_of_line_in_file)
withjot
. The process substitution<()
will make it look like a file for the interpreter, sofile1
in previous example.(I like the shuf approach above even better though - I didn't even know that existed and I would have never found that tool on my own)
This is simple.
Granted this is just a tad slower than the "shuf -n 1 file.txt" on its own.
Here's a simple Python script that will do the job:
Usage: