1

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?

Alex Krohn
  • 137
  • 6

3 Answers3

6
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.

0

With your shown samples/attempts, please try following awk code.

awk -v RS='(^|\n)123(\n|$)' 'FNR>1 && NF{print NF}' Input_file

For shown samples, output will be as follows:

3
5
1
2

Explanation:

  • In awk program setting RS(record separator) as (^|\n)123(\n|$).
  • Explanation of regex (^|\n)123(\n|$): Setting record separator as 123(which can come at starting of line OR could be followed or start with a new line OR end with 123), as per shown samples.
  • Then in main program checking condition if line number is greater than 1 AND NF(number of fields) is NOT zero then print the NF(total number of fields) for that line, which will be number of lines came between patterns.
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
0

This might work for you (GNU sed and wc):

sed -En ':a;/123/{:b;n;//!{H;bb};x;s/.(.*)/echo "\1"|wc -l/ep;z;x;ba}' file

Turn on extended regexp -E and off implicit printing -n.

Match on 123, fetch the next line, if it does not match, store the result in the hold space and repeat.

Within a substitution command, evaluate the result of the tail of the lines and count them using wc -l.

Clear the hold space, swap back to the pattern space and repeat.

potong
  • 55,640
  • 6
  • 51
  • 83