What's an easy way to read random line from a

2020-01-24 03:09发布

What's an easy way to read random line from a file in Unix command line?

13条回答
地球回转人心会变
2楼-- · 2020-01-24 03:53

Another alternative:

head -$((${RANDOM} % `wc -l < file` + 1)) file | tail -1
查看更多
冷血范
3楼-- · 2020-01-24 03:58

using a bash script:

#!/bin/bash
# replace with file to read
FILE=tmp.txt
# count number of lines
NUM=$(wc - l < ${FILE})
# generate random number in range 0-NUM
let X=${RANDOM} % ${NUM} + 1
# extract X-th line
sed -n ${X}p ${FILE}
查看更多
Deceive 欺骗
4楼-- · 2020-01-24 03:59

A solution that also works on MacOSX, and should also works on Linux(?):

N=5
awk 'NR==FNR {lineN[$1]; next}(FNR in lineN)' <(jot -r $N 1 $(wc -l < $file)) $file 

Where:

  • N is the number of random lines you want

  • NR==FNR {lineN[$1]; next}(FNR in lineN) file1 file2 --> save line numbers written in file1 and then print corresponding line in file2

  • jot -r $N 1 $(wc -l < $file) --> draw N numbers randomly (-r) in range (1, number_of_line_in_file) with jot. The process substitution <() will make it look like a file for the interpreter, so file1 in previous example.
查看更多
对你真心纯属浪费
5楼-- · 2020-01-24 04:01
sort --random-sort $FILE | head -n 1

(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)

查看更多
聊天终结者
6楼-- · 2020-01-24 04:06

This is simple.

cat file.txt | shuf -n 1

Granted this is just a tad slower than the "shuf -n 1 file.txt" on its own.

查看更多
太酷不给撩
7楼-- · 2020-01-24 04:08

Here's a simple Python script that will do the job:

import random, sys
lines = open(sys.argv[1]).readlines()
print(lines[random.randrange(len(lines))])

Usage:

python randline.py file_to_get_random_line_from
查看更多
登录 后发表回答