3

Suppose I am searching for pattern in my text file using vim. Is there a way to store 0 in a variable foo if no matches to pattern are found and store 1 if at least 1 match is found?

Thanks.

5

You can use the search() function:

When a match has been found its line number is returned. If there is no match a 0 is returned and the cursor doesn't move. No error message is given.

You probably want to set the c, w, and n flags:

c accept a match at the cursor position
n do Not move the cursor
w wrap around the end of the file

:echo search('search', 'cwn')
5127
:echo search('jabberwocky', 'cwn')
0

If you really want only 0 and 1 add > 0:

:echo search('search', 'cwn') > 0
1
:echo search('jabberwocky', 'cwn') > 0
0

If you want, you can of course make a function for this:

fun! HasPattern(p)
    return search(a:p, 'cwn') > 0
endfun

Or even a command:

:command! -nargs=1 HasPattern :echo search(<f-args>, 'cwn')>0

:HasPattern search
1
:HasPattern jabberwocky
0

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.