I have a command <streaming ls> | wc -l
, it works fine, but the <streaming ls>
takes a while, which means I don't get the final line count until a few minutes later.
Is there a way to have the output of wc -l
update in real time?
You can’t use wc -l
for this, but you can produce a running count of lines seen using other tools, for example AWK:
<streaming ls> | awk '{ printf "%d\r", NR } END { print NR }'
This will update the count of lines seen every time a line is seen, and finish with the total number of lines at the end of the process.
For commands producing lots of output, the overhead can be reduced by printing every n lines:
… | awk 'NR % 10 == 0 { printf "%d\r", NR } END { print NR }'
(for n = 10) or by printing every second:
… | awk 'systime() > lasttime { lasttime = systime(); printf "%d\r", NR } END { print NR }'
(or every n seconds by changing the condition to >= lasttime + n
).
NR % 10 == 0 { printf ...}
), and printing the exact count at the end. Even more fancy would be to print an update when a line comes in only if it's been 100 ms since the last print, maybe with an if()
inside the rule. But +1, this is a good simple starting point that's sufficient for some use-cases, like commands that produce lines somewhat slowly, or if terminal updates aren't a bottleneck.
Commented
Nov 2, 2022 at 19:19
You could use pv
to gives you some progress report:
cmd | pv -lbtr | wc -l
-l
for line-based (reports the number of lines instead of bytes).-b
to report the number bytes (well lines here because of -l
)-t
to report the time spent-r
to report the current rate (number of lines per second; see also -a
for the average rate).Beware the file names can be made of several lines, so wc -l
on the output of ls
is not guaranteed to give you a file count unless you use options like -b
or -q
which escape the newline characters in file names as \n
or ?
.
Well I used to use something like watch -n 1 your command
, not sure if that is of any use to your case, I am not a guru, just a first thing that came to my mind.
https://man7.org/linux/man-pages/man1/watch.1.html
watch - execute a program periodically, showing output fullscreen
-n, --interval seconds Specify update interval. The command will not allow quicker than 0.1 second interval, in which the smaller values are converted. Both '.' and ',' work for any locales. The WATCH_INTERVAL environment can be used to persistently set a non-default interval (following the same rules and formatting).
watch wc -l file