2009-08-25 17 views

回答

15

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支持你自己需要的幾乎所有東西。

+0

謝謝!不知道'-m'。 – seth 2009-08-25 21:43:59

2

grep「model」filename |頭-n 5> newfile中

7
grep model [file] | head -n 5 > [newfile] 
-1
cat file | grep model | head -n 5 > outfile.txt 
+5

這很可怕,在運行'grep'之前,使用'cat'將首先將整個文件加載到內存中。只需使用文件參數調用'grep'即可。 – 2009-08-25 21:41:56

+1

其他答案更好,但上面的評論是不正確的。 shell將啓動所有3個命令,而不用等待任何輸出。 – mark4o 2009-08-25 21:47:35

+1

在Windows上,管道在命令行上可用,但交易是第一個程序運行並寫入文件。然後,下一個程序運行在這些結果上。這不是Linux/Unix的工作方式。 Unix不是腦損壞的。並不是首先將整個文件讀入內存。你從哪裏得到這個想法? – xcramps 2009-08-25 21:51:55