September 4, 2011
find command

It amazing me the number of options that exist in most unix commands. Here’s my nugget for the day: Not only is regex built into find (obviously), but you can run a command on every file that find…uh, finds.

For example, you have many folders in /web/ with log files of the form *.log.#. You want to be safe and delete them one at a time:

find /web/ -regex '.*\.log\.[0-9]*$' -exec rm -vi {} \;

snore, this is slow, and boring. Lets just delete them all:

find /web/ -regex '.*\.log\.[0-9]*$' -exec rm -fv {} \;

Edit:

Here’s something else thats interesting about the find command, you can chain -exec. For example:

find /web/ -regex '.*\.log$' -exec rm -vf {} \; -exec touch {} \;

This will remove and touch all log files. A way to set all found files to 0 bytes. A nice way to clear old logs but keep them around.

I’ve read one downside of -exec is its slower than using xargs. But I never have more than a couple hundred log files so this works.

  1. chancegarcia reblogged this from mawaldne
  2. mawaldne posted this
Blog comments powered by Disqus