如何测量管道数据的大小?


16

我想做这样的事情:

> grep pattern file.txt | size -h
16.4 MB

或等同于:

> grep pattern file.txt > grepped.txt
> ls -h grepped.txt
16.4 MB
> rm grepped.txt

(虽然有点不方便)

那可能吗?

Answers:


32

您可以wc为此使用:

grep pattern file.txt | wc -c

将计算输出中的字节数。您可以对其进行后处理,以将大值转换为“人类可读”格式

您还可以pv用来在管道内获取此信息:

grep pattern file.txt | pv -b > output.txt

(以人类可读的格式显示已处理的字节数)。


1
我更喜欢,wc -c因为du -h如果读取的结果小于4,0k,则返回`4.0 K`
Stan Strum

如果以MB为单位打印输出已足够,则命令可以为| wc -c | sed 's/$/\/1024\/1024/' | bc。这将追加/1024/1024到输出并在结果字符串上运行计算器。
phil294 '19

9

您可以将pipeviewer工具pv与总字节数标志一起使用-b

$ dd if=/dev/zero bs=3 count=4211 2>/dev/null | pv -b >/dev/null
12.3KiB

$ grep pattern file.txt | pv -b >/dev/null

3

管道查看器工具是专为这一目的。如果不够灵活,则可以使用诸如和的管道操作库(libpipeline)函数调用来实现自己的FIFO数据传输测量代码。 pipeline_pump()pipeline_peek_size()

$ whatis pv
pv (1)               - monitor the progress of data through a pipe
$ pv -Wi 0.002 -cf /etc/hosts | wc -l
 367 B 0:00:00 [2.71MiB/s] 
[============================================================================>] 
100%
10
$

1

一个人可以用Python快速酿造自己的解决方案:

#!/usr/bin/env python
import sys

count = 0
while True:
    byte = sys.stdin.read(1)
    if not byte:
        break
    count =  count + 1

print(count)

如此工作:

$ echo "Hi" | ./count_stdin_bytes.py
3
$ echo "Hello" | ./count_stdin_bytes.py
6
$ dd if=/dev/zero bs=1 count=1024 2>/dev/null |  ./count_stdin_bytes.py 
1024

由于在您的特定情况下,您正在处理文本数据(从您进行管道传输的事实来看grep),因此您也可以使用bashread。像这样:

$ echo "Hello" | { while read -n 1 char; do ((count++)) ;done ; echo $count; }
6

为什么比这更好wc -cwhile read ...可能会明显变慢。此外,OP要求提供人类可读的输出,如(ls -h
phil294
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.