I'm writing a small script that needs to run a program that outputs multiple lines, and then display the count of those lines. The program, however, can take several seconds to run and I would rather not run it twice, once for the output and another for the count.
I can do it running the program twice:
#!/bin/bash
count=$(program-command | wc -l)
program-command
printf "$count lines"
Is there a way to get the count and output while only running the program once? This output has formatting, so ideally that formatting (colors) would be preserved.
wc. The wc command is used to find the number of lines, characters, words, and bytes of a file. To find the number of lines using wc, we add the -l option. This will give us the total number of lines and the name of the file.
The most easiest way to count the number of lines, words, and characters in text file is to use the Linux command “wc” in terminal. The command “wc” basically means “word count” and with different optional parameters one can use it to count the number of lines, words, and characters in a text file.
Use tee
and process substitution:
program-command | tee >(wc -l)
To preserve color, prefix the command with script -q /dev/null
as per this answer:
script -q /dev/null program-command | tee >(wc -l)
You could use awk:
program-command | awk '{print $0; count++} END {print count}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With