Delete anything other than pattern - search

Let's say this is my text:
this is my text this
is my text this is my text
my text is this
I would like to highlight all text except pattern and delete the highlighted text.
p.e. text: this must be the result.
text
texttext
text
I've found the code how to select all text except pattern:
\%(\%(.{-}\)\#!text\zs\)*
however I don't know how to delete all highlighted text.
This doesn't work:
:%s/\%(\%(.{-}\)\#!bell\zs\)*//
Can anyone help me?

Try this:
:%s/\(^\|\(text\)\#<=\).\{-}\($\|text\)\#=//g
Explanation:
\(^\|\(text\)\#<=\) # means start of line, or some point preceded by “text”
.\{-} # as few characters as possible
\($\|text\)\#= # without globbing characters, checking that we reached either end of line or occurrence of “text”.
Another way to do it:
Create a function that count matches of a pattern in a string (see :help match() to help you design that)
Use: :%s/.*/\=repeat('text', matchcount('text', submatch(0)))

Forgive me, because I'm not a vim expert, but wouldn't prepending the search with v find the inverse so that you could do something like this?
:v/pattern/d

I've implemented Benoit's clever regular expression as a custom :DeleteExcept command in my PatternsOnText plugin. It offers other related commands like :SubstituteExcept or :SubstituteInSearch, too.
OP's example would be
:%DeleteExcept /text/
Comparing that with #Benoit's explicit command (:%s/\(^\|\(text\)\#<=\).\{-}\($\|text\)\#=//g), it's a lot simpler.

Related

Vim - Find pattern on currently line ONLY

I'm wondering if there is a way to find a pattern, but restrict it to the current line. Basically, the equivalent of /PATTERN but restricted to the current line, rather than the entire document.
I've tried :s/PATTERN, but that deletes the pattern from the line and places my cursor at the beginning of the line, which is not at all what I need. I was hoping you could search without replacing...
I'm hoping to use this for a macro in order to place my cursor at the start of that pattern, as would happen when you do /PATTERN on the entire file, so anything that is macro-friendly is even better.
Any vim users out there that might have an idea?
EDIT: 0/PATTERN in a macro would work for my current need, but I'm hoping there's a more specific way to restrict the search.
ANSWER: There's a few ways posted in here so far, but the one I like best right now is using Shift+V to select the current line visually, followed by /\%V to search only in the visual selection. Then Shift+V again will turn off the visual mode.
My knowledge about macro is limited, but interactively, you can select current line with Shift + V, and then do /\%Vsearch (see http://vimdoc.sourceforge.net/htmldoc/pattern.html#/\%V).
try to Find first character of the Pattern by typing
f <letter>
It's not exactly what you need but can help to solve the problem.
/\%9lsearch
Where \%9 means line number 9.
Typing in the line number is still a bit lame. You can ctrl+r= followed by a vim expression and enter to evaluate the vim expression and insert its output. line('.') will return the line of the cursor.
In one complete step
/\%<c-r>=line('.')<cr>lsearch
For more help see:
:h /\%l
:h i_CTRL-R
Place the cursor on the line you want to search in
Select it with shift+v
Type / to begin searching
Prefix your term with \%V, e.g. \%Vabc to search for abc in only the visually selected blocks (in our case the single line)
You can search without replacing by using
:s/PATTERN//gc
Then press n to skip the replacement. If the pattern is not found, you won't even be asked.
You could also just highlight the current line or the range of lines.

Delete lines with highlighted text / delete highlighted text

Does anyone know how to delete:
lines with highlighted text
all highlighted text self
(highlighted text (p.e. after a search) not selected text)
Is there a command which search all highlighted text and delete the line?
(independent which search command or function I used to highlight text)
the g/pattern/d command does not always delete the highlighted text
p.e. /^\(.*\)\(\n\1\)\+$ --> highlight all double lines
but g/^\(.*\)\(\n\1\)\+$/d --> does NOT delete all double lines
Well, you can delete the searched pattern this way:
:%s/<pattern>//gc
And you can delete the whole line with the searched pattern this way:
:g/<pattern>/d
In addition to sixfeetsix' answer:
to delete all lines NOT containing <pattern>, type :g!/<pattern>/d or :v/<pattern>/g
to avoid having to type <pattern> after :g/, type :g/CTRL-r//d which inserts the content of the search register (CTRL-r/ means register /) into your command being typed.
how to delete: 2) all highlighted text self
You could use search-and-replace (substitute) to do this.
It is generally used like this:
:%s/your_search_here/your_replacement_here/gc
More specifically, replace your search results with nothing (to remove them):
:%s/your_search_here//gc
Omit the c at the end to replace all without confirmation.
Type :help :s for more info.
how to delete: 1) lines with highlighted text
To delete whole lines, you could either do a substitute, and just match the whole line with a regular expression (%s/^.*your_search_here.*\n//g), or you could use the multiple repeats (multi-repeat) feature.
It is generally used like this:
:g/your_search_here/[cmd]
More specifically, combine it with the normal command you use to delete a line (d):
:g/your_search_here/d
Type :help :g for more info.
Tips:
An easy way to get your query right before doing your substitute is to do your search in command mode rather than the default mode.
Instead of:
/your_search_here
Type:
:/your_search_here
Then you can go to command mode (:), hit the up key to bring up your last search, and edit the line to convert it to a substitute.
From this SuperUser answer:
You can use gn in version 7.4 onwards (and gN to go backwards). It replaces the v//e trick.
Search forward for the last used search pattern, like with `n`, and start Visual mode to select the match.
See :help gn or this Vimcast for more information.
I guess it's the essentially the same question as this:
Vim: when matching string across multiple lines using \_. in regex, yank command only works for the first line
It looks like a bug in Vim.

vim does not find and replace simple phrase that is clearly present

I have a simple vim problem that Google hasn't managed to help me with. Any thoughts are appreciated.
I do the following search and replace:
:s/numnodes/numnodes1/g
On a file containing the following text:
numprocs=0
numnodes=0
I get
E486: Pattern not found
The position of the green square which indicates where I'd start typing is clearly above the pattern. I tried searching for other short phrases not involving regex, which are also present, which also fail. A simple /numnodes highlights matches as expected. Does anyone have any idea what might be the matter with vim?
Try :%s/searchphrase/replacephase/g
Without the % symbol Vim only matches and replaces on the current line.
try using this:
:%s/numnodes/numnodes1/g

Possible to highlight matching quotes in vim?

With the syntax highlighting in vim, I get the handy feature where the matching paren or bracket will be highlighted when I put the cursor over it. Is it possible to do the same thing for quotes?
While not eloquent, one workaround is to select everything inside of matching quotes. You can do this by using the command:
vi"
This will select everything in-between the quotes. However, you won't get proper results with nested quotes as it will match the first found ".
The problem with quotes is that they are symmetrical. It would be very hard to determine which quotes belong with each other.
For instance: "Which \"quotes\" go with each other in this statement?"
This has been discussed on the vim mailing lists a few times, as well as in the bug trackers of a few of the auto-delimiter type plugins. In every case that I've seen, it's been decided that this is better left as is.
The solution is here: Stackoverflow in matchquote except it has the unfortunate limitation that only the current line is considered.
matchit seems to comes close by allowing defining of multi-line matches of words such as if/endif but still no multi-line possibility that I can figure out to get matching for " and '.
VIM already highlights quoted text in a different color, so you can easily identify strings. Do you really need it to match quotes when the whole string is already highlighted?
From :h matchparen
The characters to be matched come from the 'matchpairs' option. You
can change the value to highlight different matches. Note that not
everything is possible. For example, you can't highlight single or
double quotes, because the start and end are equal.

vi search copy paste search copy

I was just wondering if anyone could help out with how to do the following using vi.
I have a text file and it might contain something like
start of text file:
--something1.something2--
--anotherThing1.something2--
end of text file:
If I want to take this line and convert it by way of searching for anything matching the first occurrence of [A-Za-z0-9] copy that to the buffer then append it on the same line to before the first occurrent of --
start of text file:
--something1.something2.something1--
--anotherThing1.something2.anotherThing1--
end of text file:
Is there a single VI command to do this?
Cheers
Ben
:%s/--\([a-zA-Z0-9]*\).\(.*\)--/--\1.\2.\1--/gc
or without asking confirmation for every replace:
:%s/--\([a-zA-Z0-9]*\).\(.*\)--/--\1.\2.\1--/g
will produce:
--something1.something2.something1--
--anotherThing1.something2.anotherThing1--
from:
--something1.something2--
--anotherThing1.something2--
This is if you want to copy the first word after '--' up to first '.' and append '.' and word found before the last '--'.
Using vim.
RE COMMENTS:
Someone mentioned that it will not work when there are multiple words and so on.
I tested it on the following:
start of text file:
--something1.something2.something3.something4.something5.something6--
--anotherThing1.something2.anotherThing3.anotherThing4.anotherThing5--
end of text file:
after replace with the above expression:
start of text file:
--something1.something2.something3.something4.something5.something6.something1--
--anotherThing1.something2.anotherThing3.anotherThing4.anotherThing5.anotherThing1--
end of text file:
Try this:
%s:\([A-Za-z0-9]\+\)\(\..\+\)--:\1\2.\1--:g
Holy crap, in the time it took me to login to post that answer, you posted it and already got a comment!
%s/--\(\w*\)\.\(.*\)--/--\1.\2.\1--/g
--ab1.cd2..yz99-- -> --ab1.cd2..yz99.ab1--
Building on stefanB's solution but using negated character classes and the "very magic" setting, I arrive at the following substitution command:
:%s/\v--([^.]+)\.(.*)--/--\1.\2.\1--/
Depending on the exact requirements (what are allowed characters for "something1" and "anotherThing1") this might or might not be more correct.
One more thing to consider: all solutions posted so far assume that there is only one occurance of the "--text.someOtherText-- pattern per line. If this is not the case, the (.*) part of the pattern would have to be adjusted and the /g modifier is required.

Resources