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

10

227
wc -l file.txt

outputs number of lines and file name.

I need just the number itself (not the file name).

I can do this

 wc -l file.txt | awk '{print $1}'

But maybe there is a better way?

Aut answered 19/4, 2012 at 23:37 Comment(4)
wc -l < file.txt does the job precisely and concisely.Gnostic
Possible duplicate of get just the integer from wc in bashDownhaul
This is a question I've looked up twice now. This behavior of wc is unintuitive and anti-paradigmatic for -nix usual terseness. That terseness is there for a reason, because you exactly do not want to work around all kinds of fluffy redundancy. After all, I know the file name, don't I? What I want is the line count.Tybie
@Peter-ReinstateMonica You can run wc with multiple arguments (`wc -l *.txt) in which case you will get a line for each file and need to distinguish them.Come
H
319

Try this way:

wc -l < file.txt
Holpen answered 20/4, 2012 at 2:52 Comment(7)
In AIX,ksh, this will always have a space preceeding the number. We have to use | awk '{print $1}' or a cut, to trim off the spaces. Another way to trim would be to enclose with an echo.Concinnous
@Concinnous is correct, this will add a space before the number. My solution solves this and is simpler than awk or cut.Laith
@Concinnous There is no space with bash. Where does the space come from in ksh? wc -l should not emit one, and why would ksh prepend the standard output of a program with a space?Tybie
While this is the correct workaround (and it is easy enough that wc never got amended), it likely is slower and unintuitive. For one, I'd expect something like 4711 [stdin] as the output.Tybie
Also consider pairing with printf "%'d", which takes care of the space and prints out large numbers nicely.Hebel
Can someone explain why this works? What is the < doing?Denadenae
@Concinnous Interesting. Where does the space come from?Tybie
P
34
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.

Picaresque answered 19/4, 2012 at 23:41 Comment(3)
I don't like cat - concatenation consumes to much time.Aut
wc -l < file.txt has the same effect.Picaresque
@user: Test it. By far the slowest part will be reading the file off disk.Calcific
L
23

To do this without the leading space, why not:

wc -l < file.txt | bc
Laith answered 15/2, 2015 at 7:27 Comment(0)
Z
18

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).

Zecchino answered 6/11, 2018 at 17:57 Comment(4)
echo $(printf '%s' "$FOO" | wc -c) is one of the rare occasions when echo with a command subshitution isn't useless.Gine
@Gine Whoa... based on your code, echo `echo $FOO`; also acts like a String.trim() command on a variable! That's amazingly handy. I'll also add your line to my answer.Zecchino
Perhaps for context see also When to wrap quotes around a shell variableGine
... as well as Why is printf better than echo?Gine
P
12

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)

Perspire answered 1/5, 2013 at 13:57 Comment(6)
this isn't any better than the wc -l file.txt | awk '{print $1}' OP tried.Cowbell
Faster than the wc -l < file.txt method. But must use | cut -d' ' -f2 on BSD, as long as the wc command returns a leading space, example: " 34068289 file.txt", instead of "34068289 file.txt".Dorris
@Cowbell well, using awk is like using a CNC machine to cut a board instead of a saw. Use a saw for sawing.Tybie
This will not work on a Mac (BSD based). The number of leading spaces depends on the padding, so the field value will depend on the result. One of the solutions above will be much better.Biotope
@SopalajodeArrierez: Why would this be faster than the input redirection method?Hewett
@Hewett I don't know why, but on my FreeBSD v10 the test was faster . Maybe the piping is a more efficient way than input redirection due to avoid disk usage, at least on big files.Dorris
O
7

How about

grep -ch "^" file.txt
Otte answered 20/10, 2014 at 5:22 Comment(1)
Nice. Very original/creative use of grep but checking this it turns out (unsurprisingly) to be 2x to 6x slower than the simpler/straightforward wc method in my tests.Flats
T
5

Another way to strip the leading zeros without invoking an external command is to use Arithmetic expansion $((exp))

echo $(($(wc -l < file.txt)))
Templia answered 17/11, 2021 at 13:22 Comment(0)
H
4

Obviously, there are a lot of solutions to this. Here is another one though:

wc -l somefile | tr -d "[:alpha:][:blank:][:punct:]"

This only outputs the number of lines, but the trailing newline character (\n) is present, if you don't want that either, replace [:blank:] with [:space:].

Hernia answered 25/1, 2016 at 15:54 Comment(1)
This has the issue when the file name has a number in it. For example for the file test9 with 1 line in it, the output will be 19.Lassitude
S
1

Best way would be first of all find all files in directory then use AWK NR (Number of Records Variable)

below is the command :

find <directory path>  -type f | awk  'END{print NR}'

example : - find /tmp/ -type f | awk 'END{print NR}'

Swingletree answered 2/11, 2017 at 11:0 Comment(0)
C
0

This works for me using the normal wc -l and sed to strip any char what is not a number.

wc -l big_file.log | sed -E "s/([a-z\-\_\.]|[[:space:]]*)//g"

# 9249133
Coricoriaceous answered 4/9, 2019 at 7:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.