use*_*196 181 random bash shell text-processing
在bash脚本中我想从输入文件中挑出N个随机行并输出到另一个文件.如何才能做到这一点?
dog*_*ane 491
使用如下所示shuf
的-n
选项,以获得N
随机行:
shuf -n N input > output
Run Code Online (Sandbox Code Playgroud)
use*_*480 148
随机排序文件并选择第一100
行:
$ sort -R input | head -n 100 >output
Run Code Online (Sandbox Code Playgroud)
Ste*_*ven 23
好吧,根据对 shuf 回答的评论,他在一分钟内 shuff 了 78 000 000 000 行。
已接受的挑战...
编辑:我打破了自己的记录
$ time ./powershuf.py -n 10 --file lines_78000000000.txt > /dev/null
./powershuf.py -n 10 --file lines_78000000000.txt > /dev/null 0.02s user 0.01s system 80% cpu 0.047 total
Run Code Online (Sandbox Code Playgroud)
之所以如此之快,是因为我没有读取整个文件,只是将文件指针移动 10 次并在指针后打印行。
首先,我需要一个 78.000.000.000 行的文件:
$ time ./powershuf.py -n 10 --file lines_78000000000.txt > /dev/null
./powershuf.py -n 10 --file lines_78000000000.txt > /dev/null 0.02s user 0.01s system 80% cpu 0.047 total
Run Code Online (Sandbox Code Playgroud)
这给了我一个包含780 亿个换行符的文件;-)
现在是 shuf 部分:
$ time shuf -n 10 lines_78000000000.txt
shuf -n 10 lines_78000000000.txt 2171.20s user 22.17s system 99% cpu 36:35.80 total
Run Code Online (Sandbox Code Playgroud)
瓶颈是 CPU 并且没有使用多线程,它 100% 固定 1 个核心,其他 15 个没有使用。
Python 是我经常使用的,所以我将使用它来加快速度:
seq 1 78 | xargs -n 1 -P 16 -I% seq 1 1000 | xargs -n 1 -P 16 -I% echo "" > lines_78000.txt
seq 1 1000 | xargs -n 1 -P 16 -I% cat lines_78000.txt > lines_78000000.txt
seq 1 1000 | xargs -n 1 -P 16 -I% cat lines_78000000.txt > lines_78000000000.txt
Run Code Online (Sandbox Code Playgroud)
这让我不到一分钟:
$ time ./shuf.py
./shuf.py 42.57s user 16.19s system 98% cpu 59.752 total
Run Code Online (Sandbox Code Playgroud)
我在带有 i9 和三星 NVMe 的 Lenovo X1 Extreme 2nd gen 上进行了此操作,这为我提供了充足的读写速度。
我知道它可以变得更快,但我会留出一些空间让其他人尝试。
我的首选选项非常快,我采样了一个带有 13 列、23.1M 行、2.0GB 未压缩的制表符分隔的数据文件。
# randomly sample select 5% of lines in file
# including header row, exclude blank lines, new seed
time \
awk 'BEGIN {srand()}
!/^$/ { if (rand() <= .05 || FNR==1) print > "data-sample.txt"}' data.txt
# awk tsv004 3.76s user 1.46s system 91% cpu 5.716 total
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
112220 次 |
最近记录: |