user3717483
user3717483

Reputation: 49

How to search and replace the last occurrence of special character in vim

I want to achieve this :

I want to change this

./Dir/file_name1/abc.
./Dir/file_name2/def.
./Dir/file_name3/xyz.
./Dir/file_name4/pqr.

to

./Dir/file_name1/database_file
./Dir/file_name2/database_file
./Dir/file_name3/database_file
./Dir/file_name4/database_file

in vim . I am new to regular expressions in vim so please could you help me out.

Upvotes: 0

Views: 1337

Answers (5)

dvk317960
dvk317960

Reputation: 792

 %s/\(\d\)\/\S\+$/\1\/database_file/g

the expression in the parantheses matches the integer at the end of file_name at every line and will be used for back referencing while replacing the matched part with the required term 'database_file'

Upvotes: 0

kev
kev

Reputation: 161614

Yet another vim tips&tricks (if has('python')):

:py from vim import current
:py from os.path import dirname, join
:%s/.*/\=pyeval('join(dirname(current.line), "database_file")')/

Upvotes: 1

romainl
romainl

Reputation: 196486

And a :normal solution because finding the right regular expression can take too much damn time (it's a fun way to waste one's time, though):

:%norm $T/Cdatabase_file

Upvotes: 1

falsetru
falsetru

Reputation: 368944

Issue the following ex-command:

:%s,[^/]*$,database_file

The regular expression [^/]*$ matches the last part that does not contains /.

Demo: http://asciinema.org/a/10005

Upvotes: 3

Tomalak
Tomalak

Reputation: 338148

:%s/\(.*\/\).*/\1database_file/

The expression:

\(      # start group 1
  .*    #   anything, up to the end of the line
  \/    #   a forward slash (this backtracks to the last slash on the line)
\)      # end group 1
.*      # anything, up to the end of the line

Upvotes: 1

Related Questions