tags:

views:

465

answers:

4

I have a giant file where I want to find a term "model". I want to pipe the first 5 lines containing the word model to another file. How do I do that using Linux commands?

+1  A: 

grep "model" filename | head -n 5 > newfile

firedfly
+5  A: 
grep model [file] | head -n 5 > [newfile]
ghills
A: 

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

This is horrific, using `cat` will load the whole file into memory first before running `grep` . Just call `grep` with a file parameter.
Matthew Scharley
The other answers are better, but the above comment is not true. The shell will start all 3 commands without waiting for any output first.
mark4o
On Windows, pipes are available on the command line, but the deal is that the first program is run and written to a file. Then, the next program is run on those results. That's not how Linux/Unix works. Unix isn't that brain damaged. And neither reads the whole file into memory first. Where did you get that idea?
xcramps
I've been piping [z]cat to grep for many years, and I'm a creature of habit. That said, the poster did say "a giant file" and there is plenty of evidence that avoiding the call to cat can save significant time in that case
@smalloy, how would cat "save significant time"? On my system, head(1) exits when it is done, and then cat(1) harmlessly terminates from a SIGPIPE having read only the beginning of its input.
pilcrow
To memory, or to file, either will result in a significant time expenditure that results in no net gain
Matthew Scharley
+11  A: 
     grep model old_file_name.txt -m 5 > new_file_name.txt

No need for a pipe. grep supports almost everything you need on it's own.

scragar
Thanks! Didn't know about `-m`.
seth