15

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.

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

5

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
2
100GV325G<esc>
/\v%Vpattern
  • 100GV325G<esc> visually select lines from 100 to 325, return to normal 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
1

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 { of f()
  • 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 Oct 3 at 12:24
  • Thanks! 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. – dmytro.poliarush Oct 3 at 12:45
  • 1
    Ok, then I would suggest explaining how their usage is relevant and keys into the ilist – D. Ben Knoble Oct 3 at 12:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.