2

I would like to insert at the end of each line the number of alphabetic characters on that line. To do this on one line is easy. I search using :s/\a//gn and get the occurrence of alphabetic characters in the command line and then A and space and enter the number.

My problem arises when I have so many lines that it becomes extremely tedious to do this. I am trying to create a macro but am having difficulty getting command line output into it. Is there a way to do this without resorting to *nix commands? I have access to a *nix box but not all the time.

So if my file had the following content:

abc2d4s
jd4a5ag
jdf7fjf
abdd5ff

I would like the output to look like this:

abc2d4s 5
jd4a5ag 5
jdf7fjf 6
abdd5ff 6

I was thinking if there was a way to get the replace output piped into the register somehow but cannot figure out how to do it, but maybe there is a better way.

3 Answers 3

4

You can capture the output of the :s///gn command with :redir, but in this case, I would rather implement the counting via substitute() and :help sub-replace-expression:

:%s/.*/\=submatch(0) . ' ' . len(substitute(submatch(0), '\A', '', 'g'))/

This matches the entire line (.*), then removes all non-alphabetic characters (\A), and appends the length of the result. Note: Works only for ASCII characters (but \a covers only those, anyway)!

Sign up to request clarification or add additional context in comments.

1 Comment

@Kent: Thanks, I guess I saved some typing by using the inverse \A.
2

this cmd should give you that output:

%s/.*/\=submatch(0).' '.(len(submatch(0))-len(substitute(submatch(0),'\a','','g')))

Comments

2

One way to do that would be to use a simple macro:

:%norm A <C-v><C-r>=col('.')-2<C-v><CR>

which should look like:

:%norm A ^R=col('.')-2^M

where we enter insert mode at the end of each line and insert a space followed by the column number of the last character.

A variant:

:%norm A^R=" ".len(getline('.'))^M

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.