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 perform wc
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:
[ -f "$FILE" ]
Thus what we can do is iterate over all items in /etc/
and run wc
on them if and only if the above command returns true. Like so:
for i in /etc/*; do [ -f "$i" ] && wc -l "$i" ; done
find
We can also use find
with -maxdepth
, -type
, and -exec
flags
find /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 by type l
). All of that goodness is enclosed into brackets ()
escaped with \
so that shell interprets them as part of to find
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 so
$ find /etc/ -maxdepth 1 \( -type f -o -type l \) -exec wc -l {} + | tail -n 1
[sudo] password for xieerqi:
11196 total
Side-note
It's easier to just use wc -l /etc/* 2>/dev/null | tail -1
, as in
L. D. James's answer, however find
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 correctly