简体   繁体   English

使用Linux计算文本文件中的行数

[英]Count number of rows in a text file using linux

I want to know how to get the number of rows in a text file using Linux. 我想知道如何使用Linux获取文本文件中的行数。 I have tried "wc " and "wc -l ", but both display only the number of lines (columns) not the rows. 我已经尝试过“ wc”和“ wc -l”,但是都只显示行数(列)而不显示行数。 Any idea? 任何想法?

wc -l < <filename> displays lines for me wc -l < <filename>为我显示行

example file with numbers 1 - 7 示例文件编号为1-7

outputs: 输出:

scottsmudger@ns207588:~ $wc -l < test
7

From the man page: 从手册页:

-l, --lines
    print the newline counts

if you want to get the number of fields in each line you can use awk : 如果要获取每行中的字段数,可以使用awk:

  • awk reads a line from the file and puts it into an internal variable called $0 . awk从文件中读取一行并将其放入名为$ 0的内部变量中。 Each line is called record. 每行称为记录。 By default, every line is terminated by a newline. 默认情况下,每行以换行符终止。
  • Then, every record or line is divided into separate words or fields. 然后,每条记录或每一行都被划分为单独的单词或字段。 Every word is stored in numbered variables $1 , $2 , and so on. 每个单词都存储在编号变量$ 1,$ 2等中。 There can be as many as 100 fields per record. 每个记录最多可以包含100个字段。
  • awk has an internal variable called IFS (Internal Field Separator). awk具有一个称为IFS(内部字段分隔符)的内部变量。 IFS is normally whitespace. IFS通常是空白。

In this case we can use an internal built-in variable called NF, which will keep track of field numbers. 在这种情况下,我们可以使用一个称为NF的内部内置变量,该变量将跟踪字段编号。 Typically, the maximum field number will be 100. 通常,最大字段数为100。

awk '{  print NF }' file_name

this command will print the number of columns in each line 该命令将打印每行中的列数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM