How to count lines in a document?

2019-01-05 06:25发布

I have lines like these, and I want to know how many lines I actually have...

09:16:39 AM  all    2.00    0.00    4.00    0.00    0.00    0.00    0.00    0.00   94.00
09:16:40 AM  all    5.00    0.00    0.00    4.00    0.00    0.00    0.00    0.00   91.00
09:16:41 AM  all    0.00    0.00    4.00    0.00    0.00    0.00    0.00    0.00   96.00
09:16:42 AM  all    3.00    0.00    1.00    0.00    0.00    0.00    0.00    0.00   96.00
09:16:43 AM  all    0.00    0.00    1.00    0.00    1.00    0.00    0.00    0.00   98.00
09:16:44 AM  all    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00  100.00
09:16:45 AM  all    2.00    0.00    6.00    0.00    0.00    0.00    0.00    0.00   92.00

Is there a way to count them all using linux commands?

19条回答
不美不萌又怎样
2楼-- · 2019-01-05 07:20

Use nl like this:

nl filename

From man nl:

Write each FILE to standard output, with line numbers added. With no FILE, or when FILE is -, read standard input.

查看更多
女痞
3楼-- · 2019-01-05 07:23

To count all lines use:

$ wc -l file

To filter and count only lines with pattern use:

$ grep -w "pattern" -c file  

Or use -v to invert match:

$ grep -w "pattern" -c -v file 

See the grep man page to take a look at the -e,-i and -x args...

查看更多
对你真心纯属浪费
4楼-- · 2019-01-05 07:23

Redirection/Piping the output of the file to wc -l should suffice, like the following:

cat /etc/fstab | wc -l

which then would provide the no. of lines only.

查看更多
男人必须洒脱
5楼-- · 2019-01-05 07:23

As others said wc -l is the best solution, but for future reference you can use Perl:

perl -lne 'END { print $. }'

$. contains line number and END block will execute at the end of script.

查看更多
贪生不怕死
6楼-- · 2019-01-05 07:24
wc -l file.txt | cut -f3 -d" "

Returns only the number of lines

查看更多
做个烂人
7楼-- · 2019-01-05 07:25

If all you want is the number of lines (and not the number of lines and the stupid file name coming back):

wc -l < /filepath/filename.ext

As previously mentioned these also work (but are inferior for other reasons):

awk 'END{print NR}' file       # not on all unixes
sed -n '$=' file               # (GNU sed) also not on all unixes
grep -c ".*" file              # overkill and probably also slower
查看更多
登录 后发表回答