1

Say we have the following code:

Lorem ipsum.
<input name="test1">
<input name="test2"> Lorem ipsum some long text possibly so long you lose your overview.
<input name="test3">
Lorem ipsum.

Now when I do

g/name="[^"]*"/p

the output will be:

<input name="test1">
<input name="test2"> Lorem ipsum some long text possibly so long you lose your overview.
<input name="test3">

My desired output is:

name="test1"
name="test2"
name="test3"

What's the quickest way to print out ONLY the match, not the entire matching line?

3
  • 1
    I use a version similar to that one here: vim.fandom.com/wiki/… Commented May 28, 2021 at 8:34
  • Note that p is actually the independent command :p ... with no knowledge of the pattern in :g. (Some people confuse it for something more like :s///p.) If you follow :g with a command that does what you want for a single line then :g will make sure it gets run on the range of lines.
    – B Layer
    Commented May 28, 2021 at 8:36
  • One idea I've had by now is :g/name="[^"]*"/norm "Aygn to append all matches to register a. But sadly, this only works if there is at most 1 match in the line.
    – MiK
    Commented May 28, 2021 at 13:57

2 Answers 2

3

Another approach is to use the following command:

g/name="[^"]*"/echo matchstr(getline('.'), @/)
0

Be on a system with GNU Grep installed, then do:

:w !grep -o 'pattern'

The space between :w and !grep is important, because w!grep... means force-write to the file named grep ... even if it exists and is read-only.

Without using an external tool, what we can do is use a Vi implementation with decent "undo powers", like Vim. Then simply edit the buffer to show the same information. Then undo the edits when done looking at the results.

One way would be in place. First, globally delete the lines not containing the pattern:

:v/pattern/d

Then, within the remaining lines, replace everything by just the pattern:

:%s/.*\(pattern\).*/\1/

Depending on why you want to isolate just the matches, you might find this step is unnecessary, because Vim highlights the matches for a pattern. If "highlight search" happens to be disabled, use:

:set hls

Other variations on this theme might involve copying everything into a different buffer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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