This is actually fairly tricky.
I'm basing this on the GNU coreutils version of the wc
command. Note that the total
line is normally printed last, not first (see my comment on the question).
wc -l
prints one line for each input file, consisting of the number of lines in the file followed by the name of the file. (The file name is omitted if there are no file name arguments; in that case it counts lines in stdin.)
If and only if there's more than one file name argument, it prints a final line containing the total number of lines and the word total
. The documentation indicates no way to inhibit that summary line.
Other than the fact that it's preceded by other output, that line is indistinguishable from output for a file whose name happens to be total
.
So to reliably filter out the total
line, you'd have to read all the output of wc -l
, and remove the final line only if the total length of the output is greater than 1. (Even that can fail if you have files with newlines in their names, but you can probably ignore that possibility.)
A more reliable method is to invoke wc -l
on each file individually, avoiding the total
line:
for file in $directory-path/*.txt ; do wc -l "$file" ; done
And if you want to sort the output (something you mentioned in a comment but not in your question):
for file in $directory-path/*.txt ; do wc -l "$file" ; done | sort -rn
If you happen to know that there are no files named total
, a quick-and-dirty method is:
wc -l $directory-path/*.txt | grep -v ' total$'
If you want to run wc -l
on all the files and then filter out the total
line, here's a bash script that should do the job. Adjust the *.txt
as needed.
#!/bin/bash
wc -l *.txt > .wc.out
lines=$(wc -l < .wc.out)
if [[ lines -eq 1 ]] ; then
cat .wc.out
else
(( lines-- ))
head -n $lines .wc.out
fi
rm .wc.out
Another option is this Perl one-liner:
wc -l *.txt | perl -e '@lines = <>; pop @lines if scalar @lines > 1; print @lines'
@lines = <>
slurps all the input into an array of strings. pop @lines
discards the last line if there are more than one, i.e., if the last line is the total
line.
man
page forwc
doesn't mention any such functionality. You can whip up a script (or probably use pipes andawk
) to change the appearance of the output. – Karillatail +2
to skip the first line. – Chilsontotal
line if there's more than one file. And at least on my system, thetotal
line is printed last -- as POSIX specifically requires. ipo: Do you really get the output you show, with the10 total
line at the top? – Archerfish10 total
at the top because you're sorting the output. You need to mention that in the question. Show us the exact command you're running, and its exact output. And$directory-path
is not a valid variable name. – Archerfish