简体   繁体   English

如何使用bash在txt中随机行

[英]how to random lines in txt with bash

I have a txt file with some lines such as: 我有一个带有某些行的txt文件,例如:

a
b
c
f
e
f
1
2
3
4
5
6

now I want to random lines and print it to another txt file for example: 现在我想随机行并将其打印到另一个txt文件中,例如:

f
6
e
1
and so on...

could any body help me? 有人可以帮助我吗? I am new in bash scripting 我是bash脚本的新手

You could use shuf (a part of GNU coreutils). 您可以使用shuf (GNU coreutils的一部分)。

shuf inputfile > outfile

For example: 例如:

$ seq 10 | shuf 
7
5
8
3
9
4
10
1
6
2

There is an option for that 有一个选择

sort -R /your/file.txt

Expanation 扩建

-R, --random-sort -R,--random-sort

  sort by random hash of keys 

Iterate over the file, outputting each line with a certain probability (in this example, with roughly a 10% chance for each line: 遍历文件,以一定的概率输出每一行(在此示例中,每行大约有10%的机会:

while read line; do
    if (( RANDOM % 10 == 0 )); then
        echo "$line"
    fi
done < file.txt

(I say "roughly", because the value of RANDOM ranges between 0 and 32767. As such, there are slightly more values that will produce a remainder of 0-7 than there are that will produce a remainder of 8 or 9 when divided by 10. Other probabilities are have similar problems; you can fine-tune the expression to be more precise, but I leave that as an exercise to the reader.) (我之所以说“大致”,是因为RANDOM的值在0到32767之间。因此,除以RANDOM会产生0-7的余数,而剩下的值会略多于8-7的余数。 10.其他概率也有类似的问题;您可以微调表达式以使其更加精确,但我留给读者练习。

For less fortunates systems without GNU utils like BSD/OSX you can use this code: 对于没有GNU实用工具(如BSD / OSX)的不幸的系统,可以使用以下代码:

for ((i=0; i<10; i++)); do
    n=$((RANDOM%10))
    sed $n'q;d' file
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM