I want to search a string which starts with "abc" and ends with "xyz" in vim.
Below are the commands I've tried:
:1,$g/abc[\w\W]*xyz/ :1,$g/abc\[\\w\\W\]\*xyz/ :1,$g/abc*xyz/
"[\w\W]*" means the texts between "abc" and "xyz" can be any characters
"1,$" means the search range is from the 1st line to the last line in the file opened by vim.
I found that the search pattern
abc[\w\W]*xyz
works in https://regex101.com/
why does it fail in vim?
In normal mode, press / to start a search, then type the pattern ( \<i\> ), then press Enter. If you have an example of the word you want to find on screen, you do not need to enter a search pattern. Simply move the cursor anywhere within the word, then press * to search for the next occurrence of that whole word.
Using Regex in VimMany of Vim's search features allow you to use regular expressions. Some of them are: The search commands ( / and ? ) The global and substitute command-line (ex) commands ( :g and :s )
i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.
Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .
The command below should work unless "any character" means something different for you than for Vim:
:g/abc.*xyz
.
means "any character except an EOL".*
means "any number (including 0) of the previous atom".1,$
could be shortened to %
.:global
works on the whole buffer by default so you don't even need the %
./
is not needed if you don't follow :g/pattern
by a command as in :g/foo/d
.Once the file gets too large (say, 1GB), ":g/abc.*xyz" becomes quite slow.
I found that
cat fileName | grep abc | grep xyz >> searchResult.txt
is more efficient than using the search function in vim.
I know that this method may return lines that start with "xyz" and end with "abc".
But since this is a rare case in my file(and maybe this doesn't happen quite often for other people), I think I should write this method here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With