Thursday, October 13, 2022

Stop finding semicolons and start finding plus signs.

 I frequently need to use the GNU find command to recursively look through a directory. Less often, I also need to execute a command on the results. There are two well documented ways to execute that command. 

The first is to pipe the output of find into xargs and run the command there. Here's an example.

find . -iname \*yaml -print0 | xargs -0 ls -alFhtr 

The second (and a bit handier if you can remember the proper invocation) is to just add an exec to the find command. I've historically used the find, exec, {} \; method. I've just studied up on that semicolon and along the way was exposed to the find exec {} + method. It doesn't require an escape character as bash (and other shells presumably) don't have a special meaning for +. And + actually means "clomp all the find results together and pass them into the command" which is particularly handy for date comparisons and for other reasons. So try this:

find . -iname \*yaml -exec ls -alFhtr {} +
And consequently, the flags to ls now sort the grouping of files by timestamp in reverse order (leaving the most recent yaml file at the bottom of the output (which is generally what I want).