Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
2  
wc -l < /path/to/file – Cyrus Mar 3 at 19:57
up vote 7 down vote accepted

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.

share|improve this answer
    
or you could use wc -l < /etc/passwd . Same thing, just different syntax :) – Serg Mar 3 at 21:10
1  
Cheers, I'd tried using cut previously, but got hung up on using -c which wasn't useful as the line count could be of variable length. – Arronical Mar 4 at 9:47
    
Nice. I tried using cut as well, but clearly couldn't get the syntax right. – Elder Geek Mar 5 at 3:14

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.

share|improve this answer
    
Ah, I forgot to mention that the filenames may have numbers in them! – Arronical Mar 3 at 17:20
    
I've ended up using an intermediate variable, with bash expansion, so line_count=$(wc -l ${file}) then no_of_lines="${line_count/ */} – Arronical Mar 3 at 17:22
1  
Proving once again there are many ways to accomplish the same result. ;-) – Elder Geek Mar 3 at 17:24
    
I definitely prefer the simple cat usage, to save on assigning more variables. Cheers for editing the question too, was just about to get round to that. – Arronical Mar 3 at 17:28
1  
This is a useless use of cat , but it sure works :) – Serg Mar 3 at 21:09

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.