1

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!

2 Answers 2

4

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.)

2
  • Thanks a lot Andrew! Your explanation was great and it works flawlessly.
    – sidyll
    Jan 9, 2011 at 23:42
  • 1
    This is an ideal time to use the \v flag and non-/ delimiters for readability. :%s@\v^([^.]{-})/?$@\1/index.html@ Jan 10, 2011 at 2:52
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.