Suppose I want to count the lines of code in a project. If all of the files are in the same directory I can execute:
cat * | wc -l
However, if there are sub-directories, this doesn’t work. For this to work cat would have to have a recursive mode. I suspect this might be a job for xargs, but I wonder if there is a more elegant solution?
First you do not need to use
catto count lines. This is an antipattern called Useless Use of Cat (UUoC). To count lines in files in the current directory, usewc:Then the
findcommand recurses the sub-directories:.is the name of the top directory to start searching from-name '*.c'is the pattern of the file you’re interested in-execgives a command to be executed{}is the result of the find command to be passed to the command (herewc-l)\;indicates the end of the commandThis command produces a list of all files found with their line count, if you want to have the sum for all the files found, you can use find to list the files (with the
-printoption) and than use xargs to pass this list as argument to wc-l.EDIT to address Robert Gamble comment (thanks): if you have spaces or newlines (!) in file names, then you have to use
-print0option instead of-printandxargs -nullso that the list of file names are exchanged with null-terminated strings.The Unix philosophy is to have tools that do one thing only, and do it well.