gpt4 book ai didi

bash - 在文件中打印单行的最快方法

转载 作者:行者123 更新时间:2023-11-29 08:47:22 26 4
gpt4 key购买 nike

我必须从一个大文件中提取一个特定的行 (1500000 行),在多个文件的循环中多次,我问自己什么是最好的选择 (就性能而言)。有很多方法可以做到这一点,我主要使用这两个

cat ${file} | head -1

cat ${file} | sed -n '1p'

我找不到这个问题的答案是他们都只获取第一行还是两行之一(或两者)首先打开整个文件然后获取第 1 行?

最佳答案

放弃无用的 cat 并做:

$ sed -n '1{p;q}' file

这将在打印该行后退出 sed 脚本。


基准测试脚本:

#!/bin/bash

TIMEFORMAT='%3R'
n=25
heading=('head -1 file' 'sed -n 1p file' "sed -n '1{p;q} file" 'read line < file && echo $line')

# files upto a hundred million lines (if your on slow machine decrease!!)
for (( j=1; j<=100,000,000;j=j*10 ))
do
echo "Lines in file: $j"
# create file containing j lines
seq 1 $j > file
# initial read of file
cat file > /dev/null

for comm in {0..3}
do
avg=0
echo
echo ${heading[$comm]}
for (( i=1; i<=$n; i++ ))
do
case $comm in
0)
t=$( { time head -1 file > /dev/null; } 2>&1);;
1)
t=$( { time sed -n 1p file > /dev/null; } 2>&1);;
2)
t=$( { time sed '1{p;q}' file > /dev/null; } 2>&1);;
3)
t=$( { time read line < file && echo $line > /dev/null; } 2>&1);;
esac
avg=$avg+$t
done
echo "scale=3;($avg)/$n" | bc
done
done

只需保存为 benchmark.sh 并运行 bash benchmark.sh

结果:

head -1 file
.001

sed -n 1p file
.048

sed -n '1{p;q} file
.002

read line < file && echo $line
0

**结果来自包含 1,000,000 行的文件。*

因此 sed -n 1p 的时间将随着文件的长度线性增长,但其他变化的时间将保持不变(并且可以忽略不计),因为它们阅读第一行后全部退出:

enter image description here

注意:由于在更快的 Linux 机器上,时间与原始帖子不同。

关于bash - 在文件中打印单行的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15632691/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com