gpt4 book ai didi

linux - 根据行号快速提取行

转载 作者:可可西里 更新时间:2023-11-01 11:51:32 28 4
gpt4 key购买 nike

我正在寻找一种基于从 bash 中的不同文件读取的行号列表来提取文件行的​​快速方法。

定义三个文件:

position_file:包含一列整数

full_data_file:包含单列数据

extracted_data_file:包含 full_data_file 中那些行号与 position_file 中的整数匹配的行

我目前的做法是

while read position; do
awk -v pos="$position" 'NR==pos {print; exit}' < full_data_file >> extracted_data_file
done < position_file

问题是这太慢了,我正在尝试对大量相当大的文件执行此操作。我希望有人可以提出更快的方法。

感谢您的帮助。

最佳答案

使用 awk 命令的正确方法:

输入文件:

$ head pos.txt data.txt
==> pos.txt <==
2
4
6
8
10

==> data.txt <==
a
b
c
d
e
f
g
h
i
j

awk 'NR==FNR{ a[$1]; next }FNR in a' pos.txt data.txt > result.txt

$ cat result.txt
b
d
f
h
j

关于linux - 根据行号快速提取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48949531/

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