Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to stop grep output at specific count?

Status
Not open for further replies.

new2unix

Programmer
Feb 5, 2001
143
US
Hi,

Is there a way I can perform grep on multiple files, which all has the same file name prefix of "JUNK", but stop the grep after it reach specifc matching line count disregard which JUNK* file it's currently processing? Or is there another command that can do this?

Thanks

Mike
 
No easy way, but you could

for file in JUNK*
do
grep <string> $file |head -10 >/tmp/somefile
done

This would show you the first 10 entries of your string in each file.

You can customize this logic from here. If you need more direction, feel free to write back.

Bill.
 
Hi Bill,

That looks like a good start. Since I don't know how many lines in each JUNK* file would match my &quot;PATTERN&quot;, but I really only need to extract, say 10,000 matching lines from whatever number of JUNK* files it would take, I am not sure how I could keep track of the line count.

Mike
 
Lets try this one on for size. Create a shell script as follows:

#!/bin/ksh
count=0
foo=0

for file in pv.*
do
grep hdisk $file |head -10 >/tmp/somefile
foo=`wc -l /tmp/somefile|awk {'print $1'}`
count=`echo &quot;$count+$foo&quot;|bc -l`
echo $count
if [ &quot;$count&quot; -eq &quot;20&quot; ] ; then
break
fi
done

Obviously, replace &quot;pv.*&quot; with your file specification. Replace the &quot;head -10&quot; with the number of lines you wish to catch. Replace the &quot;20&quot; in the &quot;if&quot; statement with your number of hits to stop at. Let me know.

Bill.
 
Why don't you try simply
[tt]
( find /start/dir -name &quot;JUNK*&quot; -exec grep &quot;STRING&quot; {} \; ) | head -$NUMLINES
[/tt]
I hope it works...
Unix was made by and for smart people.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top