Linux中的cat命令:基本和高级示例(4)

当您将cat用于将文件内容发送到另一个命令的标准输入的唯一目的时,就会发生这种情况。 使用cat命令被称为“无用”,因为简单的重定向或文件名参数可以完成这项工作,并且可以做得更好。 但是一个值得千言万语的例子:

$ curl -so - dict://dict.org/'d:uuoc:jargon' |    sed -Ee '/^151/,/^[.]/!d;/^[.0-9]/s/.*//'  > uuoc.txt
$ cat uuoc.txt | less

UUOC


    [from the comp.unix.shell group on Usenet] Stands for Useless Use of {cat};
    the reference is to the Unix command cat(1), not the feline animal. As
    received wisdom on comp.unix.shell observes, ?The purpose of cat is to
    concatenate (or ?catenate?) files. If it's only one file, concatenating it
    with nothing at all is a waste of time, and costs you a process.?
    Nevertheless one sees people doing


    cat file | some_command and its args ...

instead of the equivalent and cheaper


    <file some_command and its args ...

or (equivalently and more classically)


    some_command and its args ... <file
[...]

在上面的例子中,我使用一个管道来显示uuoc.txt文件的内容,并使用较少的分页器:

cat uuoc.txt | less

因此,cat命令的唯一目的是使用uuoc.txt文件的内容提供less命令的标准输入。 我会使用shell重定向获得相同的行为:

less < uuoc.txt

事实上,较少的命令与许多命令一样,也接受文件名作为参数。 所以我可以简单地写一下:

less uuoc.txt

如你所见,这里不需要cat。如果我提到“无用的cat”反模式,这是因为,如果你在一个论坛或其他地方公开使用它,毫无疑问有人会指出你的论点,你会创建一个“额外的过程,什么也没有。 ”

我必须承认,很长一段时间我对这些评论都很不屑一顾。毕竟,在我们的现代硬件上,为一次性操作产生一个额外的过程不会导致那么多开销。

但在撰写本文时,我做了一个快速实验,通过测试awk脚本比较UUOC和非UUOC所需的时间来处理来自慢速媒体的500MB数据。

令我惊讶的是,差异远非微不足道,使用cat命令将数据传输到awk将导致严重的性能损失

但是,原因不是要创建额外的进程。但是由于额外的读/写和上下文切换,UUOC会产生(因为你可以从执行系统代码的时间推断它)。实际上,当您处理大型数据集时,额外的cat命令具有不可忽视的成本。至于我自己,我现在会尽力保持警惕!你呢?如果你有无用cat的例子,请不要犹豫与我们分享!

Linux公社的RSS地址https://www.linuxidc.com/rssFeed.aspx

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/12442.html