Search code examples
vimreplacevi

With VI search and replace how do I replace the text within the last two sets of single quotes?


I have a lot of lines like this:

{ id: 22, name: 'Alice', score: 123, city: 'Atlanta', birthday: '1981/12/03'},

I want to use a VI (gvim to be exact) search and replace and empty the last two sets of single quotes.


Solution

  • If you want to use search and replace, you can do this:

    :%s/city: '.\{-}'/city: ''
    

    and the same for the birthday field

    :%s/birthday: '.\{-}'/birthday: ''
    

    the "\{-}" is the same as "*" but uses de shortest match first algorithm. (see :help non-greedy)

    if you really like do this in a single command:

    %s/\(city:\|birthday:\) '.\{-}'/\1 ''/g
    

    "city:" and "birthday:" are matched as a sub-expression with the \( and \), then you can use the \1 (means the first sub-expression) in the substitute string, the end g option is needed to make more than one substitution in a single line.