linux - 如何找到文件中特定行的字节位置

标签 linux bash command-line

从命令行查找文件中特定行的字节位置的最快方法是什么?

例如

$ linepos myfile.txt 13
5283

我正在为大小为几 GB 的 CSV 编写解析器,如果解析器停止,我希望能够从上一个位置恢复。解析器在 Python 中,但即使遍历 file.readlines() 也需要很长时间,因为文件中有数百万行。我想简单地执行 file.seek(int(command.getoutput("linepos myfile.txt %i"% lastrow))),但我找不到有效执行的 shell 命令这个。

编辑:很抱歉造成混淆,但我正在寻找非 Python 解决方案。我已经知道如何通过 Python 执行此操作。

最佳答案

来自@chepner 对我的另一个回答的评论:

position = 0  # or wherever you left off last time
try:
    with open('myfile.txt') as file:
        file.seek(position)  # zero in base case
        for line in file:
            position = file.tell() # current seek position in file
            # process the line
except:
    print 'exception occurred at position {}'.format(position)
    raise

关于linux - 如何找到文件中特定行的字节位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21559181/

相关文章:

linux - 如何在终端查看期间用颜色突出显示文本日志条目(Apache、Log4J)

regex - 去除非字母数字字符的文件名

linux - Linux 中追加与连接大文件

linux - linux内核是否为实时任务执行负载平衡或任务迁移?

linux - TIdMBCSEncoding.Create ('ASCII' ) 在 Linux 上返回 MaxCharSize = 0

bash - 命令包装器和完成

linux - 命令行(甚至以编程方式)检索图像的一部分

linux - Bash(并行等待执行)

windows - 如何使用 xcopy 将文件复制到不存在的目录中?

c - 在同一端口上接收多个多播提要 - C、Linux