开发者

Adding "/index.html" to paths in Vim

开发者 https://www.devze.com 2023-02-03 02:56 出处:网络
I\'m trying to append \"/index.html\" to some folder 开发者_如何转开发paths in a list like this:

I'm trying to append "/index.html" to some folder 开发者_如何转开发paths in a list like this:

path/one/
/another/index.html
other/file/index.html
path/number/two
this/is/the/third/path/
path/five
sixth/path/goes/here/

Obviously the text only needs to be added where it does not exist yet. I could achieve some good results with (vim command):

:%s/^\([^.]*\)$/\1\/index.html/

The only problem is that after running this command, some lines like the 1st, 5th and 7th in the previous example end up with duplicated slashes. That's easy to solve too, all I have to do is search for duplicates and replace with a single slashes.

But the question is: Isn't there a better way to achieve the correct result at once?

I'm a Vim beginner, and not a regex master also. Any tips are really appreciated!

Thanks!


So very close :)

Just add an optional slash to the end of the regex:

\/\?

Then you need to change the rest of the pattern to a non-greedy match so that it ignores a trailing slash. The syntax for a non-greedy match in vim (replacing the *) is:

\{-}

So we end up with:

:%s/^\([^\.]\{-}\)\/\?$/\1\/index.html/

(Doesn't hurt to be safe and escape the period.)


Vim's regex supports the ability to match a bit of text foo if it does or doesn't precedes or follows some other text bar without matching bar, and this is exactly the sort of thing you're looking for. Here you want to match the end of line with an optional /, but only if the / isn't followed by index.html, and then replace it with /index.html. A quick look at Vim's help tells me \@<! is exactly what to use. It tells Vim that the preceding atom must be in the text but not in what's matched. With a little experimentation, I get

:%s;/\?\(index\.html\)\@<!$;/index.html;
  1. I use ; to delimit the parts of the :s command so that I don't have to escape any / in the regex or replacement expression. In this particular situation, it's not a big deal though.

  2. The / is optional, and we say so with \?.

  3. We need to group index.html together because otherwise our special \@<! would only affect the l otherwise.

0

精彩评论

暂无评论...
验证码 换一张
取 消