I want to count the total number of lines in all /etc
files but not the files in the sub directories, so I typed: wc -l /etc/* | tail -1
and the output is like:
xxxx is a directory
yyyy is a directory
total 1752
My question is, how can I rid of (delete) these comments, and is there a better way to do this type of count?
You can output the error messages to /dev/null
With this command you are only seeing the number of lines in the files that are world readable. To see the number of lines of all the files you would have to elevated the command with
sudo
.Isolate files and run wc on them
What
wc -l /etc/*
does is that*
will expand to all items inside/etc/
directory. Thus the goal is then to isolate files and performwc
on them. There are several ways to do so.for loop with test
The
test
command, or more frequently abbreviated as[
can be used to find whether an item is a regular file like so:Thus what we can do is iterate over all items in
/etc/
and runwc
on them if and only if the above command returns true. Like so:find
We can also use
find
with-maxdepth
,-type
, and-exec
flagsfind /etc/ -maxdepth 1 \( -type f -o -type l \) -exec wc -l {} +
-maxdepth
informs find how deep in the directory structure to go; value of 1 means only the files in the directory we want.-type f
tells it to look for regular files, OR (represented by-o
flag) for sybolic links (represented bytype l
). All of that goodness is enclosed into brackets()
escaped with\
so that shell interprets them as part of tofind
command , rather than something else.-exec COMMAND {} +
structure here runs whatever command we give it ,+
indicating to take all the found files and stuff them as command line args to the COMMAND.To produce total we could pipe output to
tail
like soSide-note
It's easier to just use
wc -l /etc/* 2>/dev/null | tail -1
, as in L. D. James's answer, howeverfind
should be a part of a habit for dealing with files to avoid processing difficult filenames. For more info on that read the essay How to deal with filenames correctlyfind
does that easily:Output:
BUT if you just want the number as output and nothing else:
EDIT:
newlines
error kos said prevails. Only using-exec
rectifies it. Also,/etc
doesn't contain such files.Output:
As pointed by kos, the above command can be reduced to:
EDIT:
newlines
error kos said prevails. Only using-exec
rectifies it. Also,/etc
doesn't contain such files.Output:
Using z-shell (
zsh
), the queen of the shells, instead of bash.