Unix命令获取csv文件中的行数

Dev*_*250 13 unix newline count line-numbers wc

嗨,我是UNIX新手,我必须从传入的csv文件中获取行数.我使用以下命令来计算.

wc -l filename.csv
Run Code Online (Sandbox Code Playgroud)

考虑带有1条记录的文件iam在开始时获取一些带有*的文件,如果我发出相同的命令,我将得到的数量为0.这些文件是否在这里有任何意义,如果我得到一个带有ctrlm(CR)的文件而不是NL如何获取该文件中的行数.给我一个解决问题的命令.提前致谢.

小智 44

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

cat FILE_NAME  | wc -l
Run Code Online (Sandbox Code Playgroud)

  • 这将为包含换行符的CSV文件返回错误的结果. (13认同)
  • 这应该被标记为正确的答案. (2认同)

Dan*_*ães 20

所有的答案都是错误的。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'))))"
Run Code Online (Sandbox Code Playgroud)

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";'
Run Code Online (Sandbox Code Playgroud)

我还创建了一个脚本来模拟以下输出wc -lhttps : //github.com/dhulke/CSVCount


小智 6

wc -l mytextfile

或仅输出行数:

wc -l <​​mytextfile

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
Run Code Online (Sandbox Code Playgroud)


dop*_*xxx 6

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

cat *.csv | wc -l

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