1

My question is similar to this one: How can I count the number of words in a file whilst editing the file in vim

But with a different task where I have to count characters with the search function in vim and write them at the of the file.

For example, if I have to count how many numeric characters are there, I would need something like this: :%s/[0-9]/{g} and after that a command that counts how many characters I have selected with that search.

Edit:

I'm trying a method where I first select all the characters that I want to count with /[0-9] and trying to use '<,'> like this: '<,'> !wc -m

2 Answers 2

2

If I understand you correctly, you can try this:

111
222
333
~
~ 
:redi>>%|%s/\d//gn|redi END
9 matches in 3 lines

After that, update the buffer with

:e
3
  • And \d is what I want to look for, right?
    – Ge To
    Mar 23, 2021 at 14:18
  • @GeTo Yes, I'm used to the [0-9] pattern, but \d suits better. Mar 23, 2021 at 14:20
  • I see, it was not updating the display then. But how can I display only the integer of the matches?
    – Ge To
    Mar 23, 2021 at 14:25
2

While the other answer is ok, what I wanted is simply the count of the characters written out.

This can be achieved by pipelining grep and wc:

:%!grep -o '[0-9]' | wc -l
3
  • You can accept your own answer... I think you have to wait a couple of days :) Mar 23, 2021 at 18:38
  • If you don't want to replace the contents of the editing buffer with the output of wc, use :!grep -o '[0-9]' % | wc -l instead. (% is replaced by the current buffer's filename).
    – Kusalananda
    Mar 30, 2021 at 16:04
  • And if I want to append it to the end of the file: :% !grep -o '[0-9]' | wc -l >> *file* where *file* is the file I want to append to?
    – Ge To
    Mar 31, 2021 at 12:15

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.