Count lines between "X"s

With awk:

$ awk '!/X/{count++}/X/{print count; count = 0}' input

3
4
1

Increment a count for every line not containing X; print and reset the count for lines containing X.


$ awk '/X/ && prev{print NR-prev-1} /X/{prev=NR}' file
3
4
1

How it works:

Awk implicitly reads through input files line by line.

  • /X/ && prev{print NR-prev-1}

    For any line that contains X and if we have previously assigned a value to prev, then print out the number of the current line, NR, minus prev minus one.

  • /X/{prev=NR}

    For any line that contains X, set the variable prev to the current line number, NR.


Another simple awk approach which works on OP's sample data and if X was not in first or even in last or repeated Xs.

awk -v RS='X' 'NF{print NF}' infile

Above is correct when there is only one field in each line with default FS any whitespaces, otherwise below is revised in general case for counting linewise. You can input your PATTERN in place of X there.

awk -F'\n' -v RS='X' 'NF>2{print NF-2}'

Sample input:

X
Y YYY Y
YY
YY Y YY YY Y Y
X
Y Y Y
X
Y
Y
X
X

The output is:

3
1
2