Gregg's MOTD

Tips & Tricks that I've Encountered Over the Years...

Processing The Results of The Find Command

August 19, 2023 — Gregg Szumowski

As mentioned in the previous post, the find command searches for files, but it has another very useful feature in that it can also perform an action on the files it finds.

I am a vim user, and let’s assume that I want to find my editor’s backup files in the current directory trees. These filesall end with a tilda (~) character. We would use this command to search for them:

$ find . -name '*~'
./.buffer.un~
./.find_buffer.txt.un~
./.Tips.txt.un~

which results in a list of 3 files. All it takes to remove these files is to add on a little to the end of the last command:

$ find . -name '*~' -exec rm -i '{}' \;

Now, not only will this command find all the matching files in the current directory tree, but it will also delete them.

The -exec parameter tells find to execute the command that follows it on each result. The string {} is replaced by the current file name being processed everywhere it occurs in the arguments to the command. The {} string is enclosed in single quotes to protect them from interpretation as shell script punctuation. The \; sequence indicates the end of the -exec argument.

See the manpage for more information.

Tags: cli, find, motd