Sasha
Sasha

Reputation:

How can I search in vim for a line that has 2 specific words?

I want to find a line that has both 'foo' and 'bar' in this order but not necessarily next to each other.

I tried the following and it didn't work:

/foo.*bar

Upvotes: 16

Views: 25069

Answers (3)

Mario G.
Mario G.

Reputation: 119

h: search-pattern

1. A pattern is one or more branches, separated by "\|". It matches anything that matches one of the branches.

Example: foo\|beep matches "foo" and matches "beep". If more than one branch matches, the first one is used.

2. A branch is one or more concats, separated by \&. It matches the last concat, but only if all the preceding concats also match at the same position.

Examples:
foobeep\&... matches "foo" in "foobeep".
.*Peter\&.*Bob matches in a line containing both "Peter" and "Bob"

Upvotes: 4

drrlvn
drrlvn

Reputation: 8437

Use:

:set magic
/foo.*bar

The 'magic' setting determines how VIM treats special characters in regular expressions. When it's off VIM treats all chars literally, meaning that the expression you wrote foo.*bar will actually search for that string. However, when 'magic' is on then special regex chars get their special meaning and it works more like you expect. It is recommended to always use :set magic unless dealing with really old Vi scripts, so just add it to your vimrc and you'll be set.

Upvotes: 28

Chris K
Chris K

Reputation: 12341

Works for me:

/text.*text2

Upvotes: 13

Related Questions