【问题标题】:Extract line from a file in shell script从shell脚本中的文件中提取行
【发布时间】:2015-08-16 12:00:43
【问题描述】:

我有一个 5000000 行的文本文件,我想从每 1000 行中提取一行并将它们写入一个新的文本文件。新的文本文件应该是 5000 行。

你能帮帮我吗?

【问题讨论】:

  • 哪个外壳?你试过什么?
  • 哪一行,第一行还是最后一行?
  • 请展示你的作品。

标签: shell


【解决方案1】:

我会使用 python 脚本来执行此操作。但是,您的 shell 也可以使用相同的逻辑。这是python代码。

input_file = 'path/file.txt'
output_file = 'path/output.txt'
n = 0

with open(input_file, 'r') as f:
    with ope(output_file, 'w') as o:
        for line in f:
            n += 1
            if n == 1000:
                o.write(line)
                n = 0

基本上,您初始化一个计数器,然后逐行遍历文件,为每一行递增计数器,如果计数器达到 1000,则在新文件中写入该行并重新设置计数器。

Here 是如何使用 Bash shell 遍历文件的行。

【讨论】:

    【解决方案2】:

    试试:

    awk 'NR%1000==1' infile > outfile
    

    查看此链接了解更多选项:remove odd or even lines from text file in terminal in linux

    【讨论】:

      【解决方案3】:

      您可以使用headtail,这取决于您要提取哪一行。

      从每个文件中提取第一行(例如*.txt 文件):

      head -n1 *.txt | grep -ve ^= -e ^$ > first.txt
      

      要从每个文件中提取最后一行,只需使用tail 而不是head

      提取特定行见:How do I use Head and Tail to print specific lines of a file

      【讨论】:

        猜你喜欢
        • 2011-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-14
        • 2018-06-14
        相关资源
        最近更新 更多