Bash - count and output lines from a command

I am writing a small script that should run a program that displays several lines and then displays the number of these lines. However, the program may take several seconds, and I would prefer not to run it twice, once for output, and another for counting.

I can run the program twice:

#!/bin/bash
count=$(program-command | wc -l)
program-command
printf "$count lines"

Is there a way to get an account and withdraw only when you run the program once? This output has formatting, so it’s ideal that the formatting (colors) be preserved.

+4
source share
3 answers

Use teeand substitution process :

program-command | tee >(wc -l)

To preserve color, the command prefix is script -q /dev/nullin accordance with this answer :

script -q /dev/null program-command | tee >(wc -l)
+4

awk:

program-command | awk '{print $0; count++} END {print count}'
+2

There are many ways to do something like this. My personal preference is to use the file in / tmp since I mount it in memory. This way you can write to a file and then count the line and output it very quickly.

If you do not have access to a file system with memory, try using an array to store the results so that you can use the size of the array echo ${#ArrayName[@]}, and then print it echo ${arrName[@]}.

0
source

All Articles