delete word, wih quotes, in vim

Viewed 95

if I have the following text:

['abc']

and the cursor on the first quote.

  • dw gives me [abc']
  • d2w gives me [']
  • d3w gives me [

so, how can I delete 'abc' and keep []

5 Answers
d i [ 

To delete everything inside square brackets

Use da'.

The a' text object selects the text under the cursor surrounded by single quotes, including the quotes themselves.

See :help a':

"a quoted string". Selects the text from the previous quote until the next quote.

This text object is quite smart, if there are multiple quoted strings in a line, Vim will figure out which pairs make out strings. Vim can also recognize escaped quotes inside a string (the default escape character is \, but even that you can configure through the 'quoteescape' option.)

It may be a bit counterintuitive at the start, but you can use "search&replace" for these type of tasks.

In vim, you are looking for :s Vim WiKi, find the string 'abc' and replace it with empty string.

You should use something like Don mentioned.

There are a few options for single lines:

  1. "Cut til" with ct] or "delete til" with dt]. More info is available here (you can delete backwards, yank til, etc).

  2. "Delete find" (delete through target): df'

  3. Visual line/find: Ctrl+vf'x. Verbose but gives some agency to adjust as needed.

In a comment you mention you have a multi-element list and want to remove an item. The contents of the element matter; I usually proceed in an ad-hoc manner, using combinations of dw and x or the visual line/find with w or small adjustments near the target to clip out the element in addition to techniques above.

For example, if your list is ['one', 'two', 'three'] and your cursor is over the first ', you can use dfspacebar or x2dw to produce ['two', 'three'].


Other useful threads:

While @ggorlen's answer about d f space is great, some people might find it beneficial to use a mapping which works regardless of where the cursor is position on the word, something like:

nnoremap [something] :normal vf,oF'xx<CR>

Will remove the 'one' element in the below example no matter where on the one it is.

['one', 'two', 'three'] => ['two', 'three']
Related