Nino’s Reminders

April 6, 2006

Find syntax example

Filed under: FreeBSD — nino @ 17:52

How do I find files in a directory and subdirectories and execute a command that takes found file(s) as parameter?

Easiest way is to run find command and then pipe the output to the xargs command:
find [start_dir] -name [file_mask] | xargs -I [repl_symbol] [command]

  • find [start_dir] - start from specified directory (find scans subdirectories as well). You will most often put a dot (meaning current directory) here.
  • -name [file_mask]… search files by name (if you use wildcards, be careful to escape them with a backslash - we want to have find command expand the wildcard, not the shell that is running find)
  • xargs - constructs the arguments list and executes the command
  • -I [repl_symbol]… use something as a replacement placeholder. Using percentage sign (%) seems to work ok.
  • [command]… specify a command you want to run on found files. E.g. cp % destdir will copy found file (if % is used as replacement symbol) to the destination directory.

Example
I used this little trick to find all .ko files located in various subdirectories of the current directory and copy them to a specific directory:
find . -name \*.ko | xargs -I % cp % modules/

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Blog at WordPress.com.