I want to know the size of file with .o extension (object file) in my Home folder.
I can find all the object files using
find . -name '*.o'
How can I now calculate total size of those files?
I want to know the size of file with .o extension (object file) in my Home folder.
I can find all the object files using
find . -name '*.o'
How can I now calculate total size of those files?
You're looking for pipes (
|
). They are a way of connecting multiple commands and passing the output of one command as input to another. In this case, you want to pass all the file names you find as input todu
(which calculates size). However, becausedu
expects file names and the results offind
are just a list of text (yes, the text consists of file names, butdu
can't know that, all it sees is text), you need to use something likexargs
which will take each line of text, treat it as a file name and pass that todu
. Putting all this together, we get:you should always quote the patterns you give to
find
(as I did above:"*.o"
). If you don't, the shell will expand the*.o
to the names of any matching files in the current directory. It worked in this case only because you had no matching files.The
-sch
flags fordu
are documented inman du
:Note, however, that this will fail for filenames containing whitespace. This is almost certainly not going to be an issue for object files, but in the future, if you also need to deal with spaces, use:
The
-print0
makesfind
print NULL-separated lines and the-0
makesxargs
take such lines as input.Alternatively, you can have
find
print the sizes itself and then sum them:This will also get around the problem mentioned by @Serg in the comments where there are too many arguments and the command is broken into separate commands.
If you're using
bash
(you probably are), there's a simpler way:The
shopt globstar
command makes**
match all files and or more subdirectories. After enabling it,**/*.o
will match all files (and directories) whose name ends in.o
, so we can pass that directly todu
.Note that, unlike the
find
approach, this won't match hidden files (those whose name starts with a.
). To match those as well, do:Use
-exec
flag to rundu
command with;
( meaning per each file)Sample output:
find
is recursive - meaning that it walks through all subdirectories. If you just want to get total of all*.o
files in the current directory, just dowith perl:
Size of all non-hidden PDF files in current directory.