perl -ne 'BEGIN { $pat = qr/.../; $size = (N-1) } @_ = ($_, @_[0 .. ($#_ > $size ? $size : $#_)]); print reverse @_ if /$pat/'