Using find command to interact with files

In this short article I want to show you how you can use find to interact with files within Linux. I’ll also try to cover some of the aspects when using find with xargs command and we’ll see the difference between these two. So we’ll start by playing with some of the parameters available with the find command.

Getting files older than a X number of days and remove those

find /path/to/files -mtime +60 -exec rm {} \;

You can also use the -delete option that’s available with the find command:

find . -mtime +1 -delete

If you want to search on multiple directories but want to limit the maximum depth for the search, you would use the –maxdepth parameter, just like in the following example:

find . -maxdepth 1 -mtime +1 -exec ls {} \;

Find command allows you to search for a particular type of file, such as regular files (f), directories (d), symbolic lynk (l), character devices (c) and block devices (b):

find . -type f -maxdepth 1 -mtime +30

find . -type d -maxdepth 1 -mtime +30

You can also pipe the xargs command and achieve similar results to the ones we’ve seen in the previous examples:

find . -type f -maxdepth 1 -mtime +30 | xargs ls -al

So what’s the difference between using find . -type f -maxdepth 1 -mtime +30 -exec ls -al {} \; and find . -type f -maxdepth 1 -mtime +30 | xargs ls -al  since they both seem to have similar results:


find with -exec parameter vs find with xargs command

When using find with the -exec parameter, the command will actually run the rm command for each occurrence thus creating an overhead of the whole remove process. What’s important is that when interacting with a lot of files xargs is the preferred method. Why? because when executing a command with xargs, it will actually try to run a single remove command with as much files as possible as attributes. That being said, the find with -exec parameter is much slower than find piped with xargs:

find . -exec rm \{}

find . -print0 | xargs -0 rm

So how much parameters can you fit into a single xargs command? Execute the xargs –show-limits command to view the command’s limits:


Xargs command limits

Using find command with the -exec parameter:

find /path/to/junk/files -type f -mtime +30 -exec rm -f {} \;

Using find command with the xargs command:

find /path/to/junk/files -type f -mtime +30 -print0 | xargs -0 -r rm -f