1

Let's assume that command1 is processing something and I am interested in BOTH output of command1 as well as how many lines the output actually had.

$ command1 | wc - l

prints number of lines of output of command1, while

$ command1 | nl

prints something like that:

 1  ./PaDe014
 2  ./PaDe033
 3  ./PaDe001
 4  ./PaDe013
 5  ./PaDe025
 6  ./PaDe028

See How to count lines in a document? for more solutions.

However I am interested to generate output like that:

 ./PaDe014
 ./PaDe033
 ./PaDe001
 ./PaDe013
 ./PaDe025
 ./PaDe028

Total number of files generated: 6

I have a vague feeling that it can be achieved with tee and wc, but cannot figure out how exactly.

What is the simplest way to achieve desired output?

I also tried:

command1 | tee >(wc -l)

but there must be a race condition here, as from time to time I receive strange results. Here is the test output:

pdebski@PaDe:~$ (ls -l ; printf "Total: ") | tee -a >(wc -l)
total 56
drwxr-xr-x 7 pdebski pdebski 4096 cze 22 18:50 Data
drwxr-xr-x 2 pdebski pdebski 4096 cze 22 15:14 Desktop
drwxr-xr-x 2 pdebski pdebski 4096 cze 22 14:50 Documents
drwxr-xr-x 2 pdebski pdebski 4096 cze 16 01:09 Downloads
-rw-r--r-- 1 pdebski pdebski 8980 cze 16 01:04 examples.desktop
drwxr-xr-x 4 pdebski pdebski 4096 cze 17 13:44 Music
drwxr-xr-x 2 pdebski pdebski 4096 cze 22 13:14 Pictures
drwxr-xr-x 2 pdebski pdebski 4096 cze 16 01:09 Public
drwxr-xr-x 2 pdebski pdebski 4096 cze 16 01:09 Templates
drwxrwxr-x 2 pdebski pdebski 4096 cze 22 01:21 test
drwxrwxr-x 2 pdebski pdebski 4096 cze 22 01:21 test2
drwxr-xr-x 2 pdebski pdebski 4096 cze 16 01:09 Videos
Total: pdebski@PaDe:~$ 13

A nice illustration for the need of Dijkstra's Semaphores and Mutexes, is not it? (see https://en.wikipedia.org/wiki/Edsger_W._Dijkstra )

Apparently there should be some wait here.

Same results with:

$ (ls -l && printf "Total: ") | tee -a >(wc -l)
Pawel Debski
  • 113
  • 6

2 Answers2

1

Using process substitution:

command1 | tee >(wc -l)

Or, for appending the Total number of files generated prefix:

(command1 && printf "Total number of files generated: ") | tee >(wc -l)

Reference:
https://unix.stackexchange.com/questions/28503/how-can-i-send-stdout-to-multiple-commands

valiano
  • 16,433
  • 7
  • 64
  • 79
  • Hmm, maybe not `wait` but rather 2>&1 or 3>&1 ? What do you think? – Pawel Debski Jun 23 '17 at 14:01
  • @PawelDebski Not sure what would work best for you, but check this out: https://stackoverflow.com/questions/4489139/bash-process-substitution-and-syncing – valiano Jun 24 '17 at 14:26
1

I don't know what you mean by "simplest", but for me the simplest solution is:

command1 | awk '1; END { print "\ntotal number of lines:", NR }'
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • Actually this one works: `ls -l | awk '1; END { print "Total number of lines:", NR }'` . I'd still would like to know how to really synchronise tee output streams... – Pawel Debski Jun 23 '17 at 14:06