This is a problem I had recently. I have a file with several hundred lines of text. How can I search for a string between two specific line numbers? For e.g. I want to search between line numbers 100 and 325.
4 Answers
:100,235g/foo/#<CR>
then press :147<CR>
to jump to the desired line.
You can also use :ilist
:
:100,235il foo<CR>
See :help range
, :help :global
and :help :ilist
.
There is another way to search between particular lines.
/%>{linenumber}l\%<{linenumber}{pattern}
Example:
/%>199l\%<300lgood
This will search from line 200 to 299 for the pattern 'good'.
%>199l - l is for line, >199 denotes the lines greater than 199
100GV325G<esc>
/\v%Vpattern
100GV325G<esc>
visually select lines from 100 to 325, return tonormal
mode./\v%Vpattern
use:h /\%V
to limit search ranges to last visual area.
If your pattern contains newline, you must add another \%V
to restrict pattern end in visual area:
100GV325G<esc>
/\v%Vpattern%V
:h /\%V
Sometimes you need to search for a given symbol within a function/method
void f(bool b)
{
b;
b;
}
void g(bool b)
{
b;
b;
b;
b;
}
In order to search for b
in f()
only:
- go to
{
off()
- enter visual mode with
V
- go to end of
f()
with '%' - go to exec line with ':' command.
- once you are in command line input
il b
to get:'<,'>il b
After <CR>
(enter) you get
b.cpp
1: 15 b;
2: 16 b;
Press ENTER or type command to continue
-
Welcomr to Vi and Vim! How is this substantially different from romainl’s answer?– D. Ben Knoble ♦Commented Oct 3, 2019 at 12:24
-
1Thanks! Firstly, I believe that people new to vim and not familiar with
%
and visual mode can find them useful. Secondly, there is no need to explicitly input the range of lines. Commented Oct 3, 2019 at 12:45 -
1Ok, then I would suggest explaining how their usage is relevant and keys into the
ilist
– D. Ben Knoble ♦Commented Oct 3, 2019 at 12:56