Shivam Agrawal
Shivam Agrawal

Reputation: 2103

How to only get the number of lines of a file

How do I get the number of lines of a file in linux?

I only want the number of lines, not the filename.
I want to do it in a single command, without grep or another utility.

wc -l sample.txt   

Output

5 sample.txt

Desired Output

5

Upvotes: 7

Views: 10042

Answers (7)

ecagl
ecagl

Reputation: 101

you could also do

wc -l test.txt | cut -d" " -f1

Upvotes: 0

Nathan Mella
Nathan Mella

Reputation: 11

If you want to save the output into a variable try this:

VAR=$(wc -l < sample.txt); echo ${VAR}

Upvotes: 0

Yuan He
Yuan He

Reputation: 1163

Try this

cat sample.txt | wc -l

Upvotes: 1

anubhava
anubhava

Reputation: 785128

An alternate command to print number of lines without whitespace:

awk 'END{print NR}' sample.txt

OR using grep:

grep -c '^' sample.txt

Upvotes: 1

devnull
devnull

Reputation: 123488

Other single commands to get the number of lines in a file without filename.

sed:

$ sed -n '$=' filename

awk:

$ awk 'END{print NR}' filename

Upvotes: 3

alex
alex

Reputation: 490233

If you want to strip the whitespace out too, use sed.

wc -l < file | sed 's/ //g'

Upvotes: 2

Prashant Kumar
Prashant Kumar

Reputation: 22539

Try this

wc -l < sample.txt

wc doesn't print out the filename if it reads the file through standard input. The < feeds the file via standard input.

Upvotes: 16

Related Questions