我有一个巨大的文件,想要查找术语 model。我想将包含单词 model 的前5行导入另一个文件。如何使用Linux命令实现?
答案:可以使用以下命令来实现:grep "model" 文件名 | head -n 5 > 新文件名
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 单独就支持几乎所有你需要的功能。
grep model [file] | head -n 5 > [newfile]
使用grep命令筛选出文件中包含"model"的前5个结果,并将其输出到新文件newfile中。
cat file | grep model | head -n 5 > outfile.txt
cat
命令会在运行grep
命令之前先将整个文件加载到内存中”,只需要通过文件参数直接调用grep
命令即可。 - Matthew Scharley
-m
这个参数。 - seth