I want to count the number of lines in a file using wc -l but only output the number, without the following space and filename. Edit from comments: The filename may have numbers in it.

Currently if I do:

wc -l /path/to/file 

On a file with 176 lines, the output is:

176 /path/to/file 

This is within a bash script, and the resulting number will be assigned as the value of a variable.

1

2 Answers

I'd use:

<file wc -l 

Which contarily to cat file | wc -l doesn't need to fork a shell and to run another process (and runs faster):

% time </tmp/ramdisk/file wc -l 8000000 wc -l < /tmp/ramdisk/file 0,07s user 0,06s system 97% cpu 0,132 total % time cat /tmp/ramdisk/file | wc -l 8000000 cat /tmp/ramdisk/file 0,01s user 0,16s system 80% cpu 0,204 total wc -l 0,09s user 0,10s system 94% cpu 0,203 total 

(/tmp/ramdisk/file was stored in a ramdisk to take I/O and caching out of the equation.)

However for small files indeed the difference is neglectable.


Yet another way would be:

wc -l file | cut -d ' ' -f 1 

Which in my tests performs approximately the same as <file wc -l.

3

You can do this with a simple one liner using cat. cat deluge1.log | wc -l

Answer too simple to require a long drawn out answer.

6

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy