Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim search for a pattern and if occurs delete to end of line

Tags:

regex

vim

I am trying to search a text file for a certain pattern. If this pattern occurs then it means that the rest of the line is not needed and therefore can be deleted.

I have tried using the following commands, but so far have been unsuccessful.

:%s/{pattern}/d$  :g/{pattern}/d$ 

If anyone has any suggestions they would be greatly appreciated

like image 661
smauel Avatar asked Feb 20 '09 11:02

smauel


People also ask

How delete from the end of the Vim?

To delete a line in Vi or Vim, switch to normal mode first. If you're into command mode or insert mode, you can switch back to normal mode by pressing Escape. Highlight the line that you want to delete, then hit dd or D on the keyboard.

How do I delete part of a line in Vim?

Deleting a single line in Vim editor: First, bring your cursor to the line you want to delete. Press the “Esc” key to change the mode. Now type, “:d”, and press “Enter” to delete the line or quickly press “dd”.

How do I delete a specific pattern in Vim?

In order to delete lines matching a pattern in a file using vim editor, you can use ex command, g in combination with d command. To remove lines that contains the string amos , in vim command mode, type the command below and press Enter. This will delete all lines containing the specified keywords.


2 Answers

would :%s/{pattern}.*// work?

like image 142
mirod Avatar answered Sep 27 '22 18:09

mirod


Alternatively, the following also works

:g/{pattern}/normal nd$ 

For what you want, I would go with mirod's suggestion. What I posted is a bit more flexible and might come in handy in similar situations.

Explanation:

On each line, where pattern matches, execute the following normal mode commands 'nd$'. With the cursor at the start of the line, 'n' jumps to the pattern, and 'd$' deletes to the end of the line.

like image 45
user55400 Avatar answered Sep 27 '22 19:09

user55400