Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在shell脚本中从文件中提取行_Shell - Fatal编程技术网

在shell脚本中从文件中提取行

在shell脚本中从文件中提取行,shell,Shell,我有一个5000000行的文本文件,我想从每1000行中提取一行,并将它们写入一个新的文本文件。新文本文件应为5000行 你能帮我吗 我会使用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') a

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


你能帮我吗

我会使用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,则将该行写入新文件并重置计数器

是如何使用bashshell在文件行上迭代。

可以使用head或tail,这取决于要提取的行

要从每个文件(例如*.txt文件)中提取第一行,请执行以下操作:

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

有关提取特定行的信息,请参见:。

尝试:

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

有关更多选项,请参见此链接:

哪个shell?你试过什么?哪一行,第一行还是最后一行?请展示你的作品。
awk 'NR%1000==1' infile > outfile