I have 69 files in which I want to prepend lines 5 to penultimate with a short string. How could I address the penultimate line? :5,61s/^/X/g would do it if I manually look up that the last line is 62, but if I want to script it for all the files, how can I do that? I could imagine doing something like vim "+:5,$((`cat test.txt|wc -l` - 1))s/^/X/g|:x" test.txt from the command line, but as I'm not dealing with a simple search and replace as in my above example I think I won't be able to provide it from the command line, how can I do it from within vim?

  • 3
    $-1 could be used to express the second to last line. Does :5,$-1s/^/X work for you? May 10 '16 at 12:35
  • @user9433424 Yes, that seems to be working.
    – muk.li
    May 10 '16 at 12:38

You can express the penultimate line with $-1. So, in your case, to prepend X in front of all the lines from the fifth down to the second to last one, you could use the following substitution command:


You can find more information on how to write a range in :help :range.

  • 2
    -1 in a range can be shorted to - as the 1 can be assumed. e.g. :5,$-s/^/X May 10 '16 at 14:12

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.