1

How can I count the rows between patterns and redirect the rows count on file?

example:

PATTERN FOUND 
rows 
rows 
rows 
PATTERN FOUND 
rows 
rows

Expected result should be:

3
2
  • Is the answer 3 or 3,2? – Jeff Schaller Apr 19 '18 at 13:49
  • the answer that i expect is: 3,2,x,n,y etc..etc.. – Luca Apr 19 '18 at 13:57
  • what does "redirect the raw counts on file" mean? – Jeff Schaller Apr 19 '18 at 14:05
  • for example cat pattern_file | while read lines; do <some command tath return the number of line> > OUT_FILE_COUNT_RAW; done – Luca Apr 19 '18 at 14:10
2

Using awk:

$ awk -v RS='PATTERN FOUND' 'NF{print NF}' infile
3
2

Or if your rows are actually a set of sentences, you can do:

$ awk -v RS='PATTERN FOUND' -F'\n' 'NF{print NF-2}' infile >output

Above awk on below sample input file:

PATTERN FOUND
rows
rows
rows
PATTERN FOUND
rows
rows
Here PATTERN FOUND :
zero first
second

fourth fifth sixth and last

Will give you the result:

3
2
4

To get rid of empty lines and don't count them:

awk -v RS='PATTERN FOUND' -F'(\n)+' 'NF{print NF-2}' infile

and to get rid of empty lines and those contains only whitespace (Tabs or Spaces):

awk -v RS='PATTERN FOUND' -F'(\n|^[ \t]*$)+' 'NF{print NF-2}' infile
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.