【问题标题】:Unix Command to get the count of lines in a csv fileUnix命令获取csv文件中的行数
【发布时间】:2014-04-26 01:55:06
【问题描述】:

您好,我是 UNIX 新手,我必须从传入的 csv 文件中获取行数。我已经使用以下命令来获取计数。

wc -l filename.csv

考虑带有 1 条记录的文件 iam 在开始时获取一些带有 * 的文件,如果我发出相同的命令 iam 得到计数为 0,那么对于这些​​文件。* 是否意味着这里以及如果我得到一个带有 ctrlm(CR) 的文件) 而不是 NL 如何获取该文件中的行数。给我一个解决问题的命令。提前致谢。

【问题讨论】:

  • some files with * at the start 这是否意味着* 是文件中的唯一字符(或)文件还有其他内容?
  • 文件有其他内容但起始字符为*(星号)

标签: unix count newline line-numbers wc


【解决方案1】:

以下查询可帮助您获取计数

cat FILE_NAME  | wc -l

【讨论】:

  • 这将为包含换行符的 CSV 文件返回不正确的结果。
【解决方案2】:

wc -l 我的文本文件

或者只输出行数:

wc -l

Usage: wc [OPTION]... [FILE]...
or:  wc [OPTION]... --files0-from=F
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.
  -c, --bytes            print the byte counts
  -m, --chars            print the character counts
  -l, --lines            print the newline counts
  --files0-from=F    read input from the files specified by
                       NUL-terminated names in file F;
                       If F is - then read names from standard input
  -L, --max-line-length  print the length of the longest line
  -w, --words            print the word counts
  --help     display this help and exit
  --version  output version information and exit

【讨论】:

    【解决方案3】:

    如果您在同一个文件夹中有多个 .csv 文件,请使用

    cat *.csv | wc -l

    获取当前目录中所有csv 文件的总行数。所以, -c 对字符进行计数,-m 对字节进行计数(只要您使用 ASCII 就相同)。您也可以使用wc 来计算文件的数量,例如作者:ls -l | wc -l

    【讨论】:

      【解决方案4】:

      所有答案都是错误的。 CSV 文件接受引号之间的换行符,但仍应将其视为同一行的一部分。如果你的机器上有 Python 或 PHP,你可以这样做:

      Python

      //From stdin
      cat *.csv | python -c "import csv; import sys; print(sum(1 for i in csv.reader(sys.stdin)))"
      
      //From file name
      python -c "import csv; print(sum(1 for i in csv.reader(open('csv.csv'))))"
      

      PHP

      //From stdin
      cat *.csv | php -r 'for($i=0; fgetcsv(STDIN); $i++);echo "$i\n";'
      
      //From file name
      php -r 'for($i=0, $fp=fopen("csv.csv", "r"); fgetcsv($fp); $i++);echo "$i\n";'
      

      我还创建了一个脚本来模拟wc -l的输出:https://github.com/dhulke/CSVCount

      【讨论】:

      • 对于某些字段中带有换行符的 csv 文件,这是唯一正确的答案(有效)
      • 这是怎么回事。 OP 说的是 unix 命令,而不是编程语言中的一种方式。
      • 因为 Python 存在于大多数 unix 系统中,例如 awk、wc 和其他程序。
      猜你喜欢
      • 2020-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-01
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多