Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all text in line before/after highlighted search pattern

Tags:

vim

search

I know in VIM how to search a string and delete the text till the start/end of line but I would like to know if it is also possible to delete all text in line before or after highlighted search pattern.

like image 642
Reman Avatar asked Jun 03 '11 09:06

Reman


3 Answers

To delete the text before FOO on the same line:

:s/^.*\(FOO\)/\1/

like image 191
xofon Avatar answered Nov 15 '22 22:11

xofon


If you want to do this across all lines and don't want to retype your search term I'd suggest the following:

:%s/.*\ze<Ctrl-r>///

What this does is:

  • %s/: substitute across all lines in a file
  • .*: match any character
  • \ze: end matching so the rest of the pattern is not substituted
  • <Ctrl-r>/: insert text from the '/' register (which is the search register)
  • //: replace with nothing

Edit: Forgot about the after part. My suggestion to remove both at the same time would be:

:%s/.*<Ctrl-r>/.*/<Ctrl-r>//
like image 14
Randy Morris Avatar answered Nov 15 '22 23:11

Randy Morris


From beginning of line to the beginning of highlighted search pattern: 0dn

From after end of highlighted search pattern to the end of line: $N//e<Enter>lD

These will work in most of the cases.

like image 2
usta Avatar answered Nov 15 '22 22:11

usta