7

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.

Elder Geek
  • 35,476
  • 25
  • 95
  • 181
Arronical
  • 19,653
  • 18
  • 73
  • 128

4 Answers4

13

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.

kos
  • 35,535
  • 13
  • 101
  • 151
5

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.

Elder Geek
  • 35,476
  • 25
  • 95
  • 181
0

another cleaner option wc -l filename | awk '{print $1}

example list of entries in a file

bash-4.1$ wc -l ../CBB_Nodes.txt | awk '{print $1}' 
398
bash-4.1$ 
without awk it would have been as usual with the file name. 

bash-4.1$ wc -l ../CBB_Nodes.txt
398 ../CBB_Nodes.txt
bash-4.1$ 
0

Another simple alternative that did the trick for me.

cat /c/dev/P2Working/.gitignore | wc -l

enter image description here