bashawksed

How to iteratively find number of lines between two patterns?


This question is similar, but distinct from 1, 2, and 3.

Instead of pasting the lines in between the two patterns, I want to iteratively count the lines.

For example, given file.txt with these strings

abc
123
daafsd
asdfas
asdcasdfa
123
sdfasdc
asdfasdcasd
asdfasdfasdf
asdfasdfasdf
ascasdcasdcasd
123
asdcasdfacasdcas
123
asdfasdcasdcasc
asadfasdfas
123

I would want to count the lines between the pattern of 123. So, the expected output would be:

3
5
1
2

Any suggestions?


Solution

  • awk '$0=="123" {if (n) print NR-1-n; n=NR}' file
    

    This uses the line number of matched lines to print the number of lines between them.