Linux command: find files and run command on them

command linelinux

How do I manage to find all files in a directory and subdirectories and run a command on them?

For example,

find . -type f -name "*.txt" 

finds all txt files and:

find . -type f -name "*.txt" | gedit

sends it to gedit, but inside a text file. I want gedit to open all text files.

Best Answer

You can use the -exec flag to execute a command on each matching file:

$ find ./ -type f -name "*.txt" -exec gedit "{}" \;

Syntax

The syntax is a bit strange (see -exec command ; in the manpages for more):

The string `{}' is replaced by the current file name being processed

You may also want to consider -execdir, which will do the same, but executes the command from the subdirectory containing the matched file (this is generally preferable).

Related Question