2

I am using the following regex to find the first letter of the last word on each line in a file:

%s/.* .\zs/

I want to now lower case this match on every line in a file. How do I do it?

For eg.

Before: Insomnia Cures

After : Insomnia cures

3 Answers 3

2

This worked for me

%s/.*\zs \([A-Z]\)/\L&/

If you want to consider lines like

Insomnia (Cures)

you can use %s/.*\zs [^A-Z]\?\([A-Z]\)/\L&/

To manipulate strings at the beginning of the line you can use %s/^\([^a-z][A-Z]\)/\L&/

1
  • 2
    Welcome to Vim. We recommend you to add some explanation to your answer to guide the readers. Jul 9 at 6:48
2

For this specific task, an alternative approach is not to use a :substitute command at all!

:%norm!$Bgul

 %             # On every line,
  norm!        # Run the normal mode commands:
       $       # Move to the end of the line,
        B      # Move to the start of the last WORD on the line, and
         gu    # Convert to lower case...
           l   # The first letter of the word.
2

You could do the following:

:%s/\S\+\s*$/\l&/

The \S\+ match any non space characters (a word)

Since its is followed by \s*$, that only match trailing spaces at the end of the line, this word must be at the end of the line.

The \l transforms the match by changing the first letter to lowercase.

You can find more information at: :help :s% for the transformation possibilities.

You can find also more information about patterns at :help pattern-overview.

2
  • Thanks @Rich it seems I read the question toi fast :-/ Aug 10 at 5:21
  • 1
    We've all been there!
    – Rich
    Aug 10 at 9:14

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.