我想随机洗牌文本文件的行,并创建一个新文件。该文件可能有几千行。
我如何用cat, awk, cut等做到这一点?
我想随机洗牌文本文件的行,并创建一个新文件。该文件可能有几千行。
我如何用cat, awk, cut等做到这一点?
当前回答
这是第一次尝试,对编码器来说很容易,但对CPU来说很难,它在每行前加上一个随机数,对它们进行排序,然后从每行中剥离随机数。实际上,这些行是随机排序的:
cat myfile | awk 'BEGIN{srand();}{print rand()"\t"$0}' | sort -k1 -n | cut -f2- > myfile.shuffled
其他回答
Ruby增值:
ls | ruby -e 'puts STDIN.readlines.shuffle'
在windows下,您可以尝试此批处理文件来帮助您洗牌data.txt,批处理代码的用法是
C:\> type list.txt | shuffle.bat > maclist_temp.txt
发出这个命令后,maclist_temp.txt将包含一个随机的行列表。
希望这能有所帮助。
一种简单而直观的方法是使用shuf。
例子:
假设words.txt为:
the
an
linux
ubuntu
life
good
breeze
要洗牌,请执行以下操作:
$ shuf words.txt
这将把打乱的行扔到标准输出;所以,你必须将它管道到一个输出文件,就像:
$ shuf words.txt > shuffled_words.txt
一次这样的洗牌可能会产生:
breeze
the
linux
an
ubuntu
good
life
这是第一次尝试,对编码器来说很容易,但对CPU来说很难,它在每行前加上一个随机数,对它们进行排序,然后从每行中剥离随机数。实际上,这些行是随机排序的:
cat myfile | awk 'BEGIN{srand();}{print rand()"\t"$0}' | sort -k1 -n | cut -f2- > myfile.shuffled
如果你像我一样来这里寻找一个替代的macOS洗牌,那么使用随机行。
安装随机行(自制)包,其中有一个rl命令,具有类似于shuf的功能。
酿造安装随机行
Usage: rl [OPTION]... [FILE]...
Randomize the lines of a file (or stdin).
-c, --count=N select N lines from the file
-r, --reselect lines may be selected multiple times
-o, --output=FILE
send output to file
-d, --delimiter=DELIM
specify line delimiter (one character)
-0, --null set line delimiter to null character
(useful with find -print0)
-n, --line-number
print line number with output lines
-q, --quiet, --silent
do not output any errors or warnings
-h, --help display this help and exit
-V, --version output version information and exit