9

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.

muru
  • 207,228
Arronical
  • 20,241

4 Answers4

15

I'd use:

<file wc -l

Which unlike cat file | wc -l won't run an additional process nor fork two additional subshells (in turn running 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 speed and caching out of the equation.)

For small files the difference would be neglectable.


Yet another way would be:

wc -l file | cut -d' ' -f1

Which in my tests performed approximately the same as <file wc -l, or:

sed -n '$=' file

Which will print the correct number of lines in case the file is missing a trailing newline.

kos
  • 41,268
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
  • 36,752
2

Another cleaner option:

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

Example for a list of entries in a file:

bash-4.1$ wc -l ../CBB_Nodes.txt | awk '{print $1}' 
398

Without Awk it would have been printed, as usual, with the file name.

bash-4.1$ wc -l ../CBB_Nodes.txt
398 ../CBB_Nodes.txt 
kos
  • 41,268
1

Another variation using a single command

$ awk 'END{print NR}' your_file_name

Provides accurate results than wc -l when last line does not have newline. Avoids UUOC but might need a lengthy comment in the code explaining why the h**l wc is not used!