Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash - count and output lines from command

Tags:

bash

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.

like image 370
steel Avatar asked Apr 15 '16 16:04

steel


People also ask

How do I count lines in bash?

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.

How do I count the number of lines in terminal?

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.


2 Answers

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)
like image 72
Ben Avatar answered Sep 29 '22 10:09

Ben


You could use awk:

program-command | awk '{print $0; count++} END {print count}'
like image 30
Razvan Avatar answered Sep 29 '22 11:09

Razvan