zoukankan      html  css  js  c++  java
  • 情景linux--wc -l是用来统计文件行数的吗?

    转自:https://www.jianshu.com/p/19d97bd9f9d5

    情景

    在linux,如果希望快速得到一个文件的行数,我想wc -l一定会被优先想到。那么,它真的是用来统计文件行数的么?

    查看如下文件:

    $ cat a.txt 
    

    结果:

    1
    2
    3
    

    尝试查看行数:

    $ wc -l a.txt 
    
    3 a.txt
    

    如此看来,wc -l可以统计文件行数。

    再看另外一个例子:

    $ cat b.txt 
    
    1
    2
    3
    4$
    

    结果中的$并不是b.txt文件的内容,而是b.txt的最后一行没有换行,所以和linux的命令提示符显示在了同一行上。

    尝试查看行数:

    $ wc -l b.txt 
    
    3 b.txt
    

    结果却是3行。

    为了看清楚两个文件的内容,使用od -tc命令查看:

    $ cat a.txt | od -tc
    0000000   1  
       2  
       3  
    
    0000006
    
    
    $ cat b.txt | od -tc
    0000000   1  
       2  
       3  
       4
    0000007
    
    

    可见,在b.txt中,数字4后面没有 字符。

    结论

    现在应该弄清楚wc -l命令的含义了吧?

    wc -l原本就不是用来查看行数的,而是用来查看文件的newline的数量的。

    其实,在wc的man手册中说的很清楚:

    $ man wc
    
    NAME
           wc - print newline, word, and byte counts for each file
    ...
    
    DESCRIPTION
           Print  newline, word, and byte counts for each FILE, and a total line if more than one FILE is specified.  With
           no FILE, or when FILE is -, read standard input.
    ...
           -l, --lines
                  print the newline counts
    

    而在linux系统中,newline字符就是 字符。

    扩展知识

    强烈建议亲手执行一遍上述命令。

    你可能会问,如何做到让文件的最后一行内容不带newline字符呢?

    使用echo -n即可:

    $ man echo
    
    NAME
           echo - display a line of text
    
    ...
    
           -n     do not output the trailing newline
    

    echo -n将不输出尾部的newline字符。

    举例:

    $ echo -n "1" > c.txt
    
    $ cat c.txt | od -tc 
    0000000   1
    0000001
    
    
    $ wc -l c.txt 
    0 c.txt
    

    你看,文件中明明有内容,用wc -l得到的结果却是0——曾经让我困惑的真实经历。



    作者:软件测试技能栈
    链接:https://www.jianshu.com/p/19d97bd9f9d5
    来源:简书
    简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

  • 相关阅读:
    “能用”距离“好用”有多远?
    序列化到底是神马?
    新版Microsoft Azure Web管理控制台
    玩转Windows Azure存储服务——高级存储
    Windows 10 Threshold 2 升级记录
    玩转Windows Azure存储服务——网盘
    Windows Azure HDInsight 使用技巧
    Docker on Microsoft Azure
    Azure Linux VM Swap 分区
    Google Cloud Platform
  • 原文地址:https://www.cnblogs.com/xxj-bigshow/p/10832690.html
Copyright © 2011-2022 走看看