With awk awk 'x&&/S/{exit}x+=/R/' file Example seq 20 | awk 'x&&/1/{exit}x+=/6/' 6 7 8 9