使用Linux命令获取符合某个模式的前n行

4

我有一个巨大的文件,想要查找术语 model。我想将包含单词 model 的前5行导入另一个文件。如何使用Linux命令实现?

答案:可以使用以下命令来实现:
grep "model" 文件名 | head -n 5 > 新文件名
4个回答

16

man grep提到:

 -m NUM, --max-count=NUM
          Stop reading a file after NUM matching lines.  If the  input  is
          standard  input  from a regular file, and NUM matching lines are
          output, grep ensures that the standard input  is  positioned  to
          just  after the last matching line before exiting, regardless of
          the presence of trailing context lines.  This enables a  calling
          process  to resume a search. 

因此可以使用

grep model old_file_name.txt -m 5 > new_file_name.txt

不需要使用管道。grep 单独就支持几乎所有你需要的功能。


谢谢!我不知道 -m 这个参数。 - seth

7
grep model [file] | head -n 5 > [newfile]

2

使用grep命令筛选出文件中包含"model"的前5个结果,并将其输出到新文件newfile中。


-1
cat file | grep model | head -n 5 > outfile.txt

5
这太可怕了,“使用cat命令会在运行grep命令之前先将整个文件加载到内存中”,只需要通过文件参数直接调用grep命令即可。 - Matthew Scharley
1
其他答案更好,但上面的评论是不正确的。Shell将启动所有3个命令,而无需等待任何输出。 - mark4o
1
在Windows上,管道可以在命令行上使用,但是首先运行第一个程序并将其写入文件。然后,下一个程序在这些结果上运行。这不是Linux / Unix的工作方式。Unix并不那么脑残。也没有一个会先将整个文件读入内存。你从哪里得到这个想法的? - xcramps
1
我已经使用[z]cat管道到grep很多年了,我习惯性地这样做。话虽如此,发布者确实说了“一个巨大的文件”,有足够的证据表明避免调用cat在那种情况下可以节省大量时间。 - user47559
@smalloy,"cat如何节省大量时间"?在我的系统上,head(1)完成后退出,然后cat(1)从一个SIGPIPE中无害地终止,只读取了其输入的开头部分。 - pilcrow
将数据存储到内存或文件中,都会导致显著的时间开销,而这并不会带来任何净收益。 - Matthew Scharley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接