Implementation method of shell randomly extracting several lines from file

Time:2021-9-23

shuf -n5 main.txt

sort -R main.txt | head -5

awk -vN=5 -vC=”`wc -l file`” ‘BEGIN{srand();while(n<N){i=int(rand()*C+1);if(!(i in a)){a[i]++;n++}}}NR in a’ file

while read line;do echo “$line $RANDOM”;done < main.txt | sort -k2,2n| awk ‘NR<=5{print $1}’

Options for the shuf command:

-e. — echo: treat each parameter as an input line
-i. — input range = lo-hi: treat each number from lo to hi as an input line
-n. — head count = number of rows: output the specified number of rows at most
-o. — output = file: output the results to the specified file instead of standard output
–Random source = file: get random bits from the specified file
-z. — zero terminated: end the line with 0 instead of a new line
–Help: display this help message and exit
–Version: display version information and exit

Example: