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
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.
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”.
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.
would :%s/{pattern}.*//
work?
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.
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