0

I can get a word count of a range of lines, by doing something like this:

:1,20w !wc -w

(where that gets lines 1 to 20, writes (w) them to the external shell command (!) wc -w, and outputs the result in the info area.

I can set the result of a shell command to a variable if I do something like this:

:let wc = system('wc -w')

(so then if I issue the command :echo wc, it displays..., ah, 0 in the info area, because I didn't give wc any text to parse.

So how do I tell the system command which lines to pass to the external shell command it calls?

2
  • 1
    :help system() takes input (though you'd probably rather use systemlist()). Use getline() or getbufline() to get lines from a buffer
    – D. Ben Knoble
    Commented Oct 24, 2022 at 19:39
  • 3
    Have you considered/tried using wordcount() instead? (Not 100% sure if it will work: you'd need to set visual mode in order to apply it to your range.)
    – Rich
    Commented Oct 26, 2022 at 11:07

1 Answer 1

1

Pass the lines to be piped to the shell command via an arg to the system function call:

:let wc=system('wc -c',getline(1,20))

As, @d-ben-knoble suggested, care of the system function help page.

1
  • 1
    Note that the wc variable here ends with a newline (\n), as that's what wc will output, which can be real confusing if you use it for comparison or echo'ing later. You probably want to call trim() on the output to remove it like so: :let wc = system('wc -c', getline(1, 20))->trim() Commented Oct 26, 2022 at 11:21

Your Answer

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

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