shell - How to get "wc -l" to print just the number of lines without file name?

ID : 20438

viewed : 26

Tags : shellwcshell

Top 5 Answer for shell - How to get "wc -l" to print just the number of lines without file name?

vote vote

95

Try this way:

wc -l < file.txt 
vote vote

89

cat file.txt | wc -l 

According to the man page (for the BSD version, I don't have a GNU version to check):

If no files are specified, the standard input is used and no file name is displayed. The prompt will accept input until receiving EOF, or [^D] in most environments.

vote vote

77

To do this without the leading space, why not:

wc -l < file.txt | bc 
vote vote

65

How about

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

i.e. pipe the output of wc into cut (where delimiters are spaces and pick just the first field)

vote vote

60

Comparison of Techniques

I had a similar issue attempting to get a character count without the leading whitespace provided by wc, which led me to this page. After trying out the answers here, the following are the results from my personal testing on Mac (BSD Bash). Again, this is for character count; for line count you'd do wc -l. echo -n omits the trailing line break.

FOO="bar" echo -n "$FOO" | wc -c                          # "       3"    (x) echo -n "$FOO" | wc -c | bc                     # "3"           (√) echo -n "$FOO" | wc -c | tr -d ' '              # "3"           (√) echo -n "$FOO" | wc -c | awk '{print $1}'       # "3"           (√) echo -n "$FOO" | wc -c | cut -d ' ' -f1         # "" for -f < 8 (x) echo -n "$FOO" | wc -c | cut -d ' ' -f8         # "3"           (√) echo -n "$FOO" | wc -c | perl -pe 's/^\s+//'    # "3"           (√) echo -n "$FOO" | wc -c | grep -ch '^'           # "1"           (x) echo $( printf '%s' "$FOO" | wc -c )            # "3"           (√) 

I wouldn't rely on the cut -f* method in general since it requires that you know the exact number of leading spaces that any given output may have. And the grep one works for counting lines, but not characters.

bc is the most concise, and awk and perl seem a bit overkill, but they should all be relatively fast and portable enough.

Also note that some of these can be adapted to trim surrounding whitespace from general strings, as well (along with echo `echo $FOO`, another neat trick).

Top 3 video Explaining shell - How to get "wc -l" to print just the number of lines without file name?

Related QUESTION?