Find… and Exec

In the last two posts, we talked about finding things. The result of that find command was a list of filenames or directory names… just lists of things. Which is useful if we want to know ‘where did I leave that file’. But I want to do things with these files. Suppose I want to know when all files that have an ‘s’ in them were last accessed. I could do that by finding all of those files and then doing ls -l on each one. But I’m lazy, I don’t want to do that.

As I’ve said many times, there’s more than one way of doing things in Linux. You can do things the long and complicated way or you can learn a little about the command line and do things the short and fast way. Let’s talk about that short and fast way and get to the end result. I’m lazy. I don’t want to type the same thing over and over again. Luckily, find lets me get away from that. See?

find . -name '*s*' -exec ls -l {} \;

So I’m finding all files that have an s in them, just like I’ve done before. Now, though, I’m adding a new flag, -exec. After that flag, I give the command I want. The {} means take the output of the find and put that value in those brackets. So it’s going to do ls -l on every file it finds.

One command to take care of all those commands I listed before, isn’t that neat?

Now let’s pretend I want to rid my system of all sith. Those sith infested my system with lots of files, all of them with the name sith (or some variant thereof) and I’ve got to get rid of them.

find / -iname '*sith*' -exec rm {} \;

So I find any file with the name sith or Sith or DarthSith or SithofDarkness or even sItH… and I remove them. All go away and I don’t even need to find my lightsaber.

Leave a Reply

Your email address will not be published. Required fields are marked *