Question about grep

is there anyway i can ask grep to only get the first line?
as in the top command line

line 1 <-- just grep this line
line 2
line 3

---------- Post updated at 04:24 PM ---------- Previous update was at 04:19 PM ----------

nvm.. found out that i can do it with

|head

If you only want to search the first line of a file, you could do:

head -1 file | grep pattern

as opposed to getting the first line of the search results for the whole file, which would be

grep pattern file | head -1

(although you might be able to do either just with grep, depending on the options your implementation has)

head -1 filename | grep "string"

However, this is faster for large files:

sed -n '1,1p;1q' bigfile | grep "string"
1 Like

ah great... hmm sed , time to look up sed

btw the size of directory without sub is

du -S

that's what i got from the linux library i've been reading.
but for some reason when i type that in my system it doesnt work.. maybe cause im using bourne shell?
there should be an alternate way right? can give me a hint?

"doesn't work" is not exactly descriptive. You get an error message, blank output, or what?

1 Like

@ Carlom - yes as balajesuri said, it's not supported. no such option

@balajesuri , oh i see, need to write that down for future reference.

Thanks again CarloM and balejesuri

sed '/string/!d;q' inputfile

thanks ctsgnb, for the sed, still learning to use sed. That sed code will become handy to me .

 
awk '/pattern/ {print;exit}' input.txt
1 Like

Could be shorten:

sed 'q' bigfile | grep "string"
sed '/string/!d;q' bigfile
1 Like

thanks again itkamaraj and ctsgnd

sed 'q' bigfile | grep "string"
Nice post. Been looking for that one for a long time.

Any way of reading just the first line of a big file quickly is really useful. This has to be the shortest code.

Not so sure about this one because it searches the entire file if the string is not found:
sed '/string/!d;q' bigfile

For a 600 Mb text file:

time sed 'q' bigfile | grep "string"

real        0.0
user        0.0
sys         0.0

time sed '/string/!d;q' bigfile

real       47.7
user       39.2
sys         8.4
1 Like

-- deleted --