Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

share|improve this question

migrated from stackoverflow.com Mar 15 '13 at 1:07

This question came from our site for professional and enthusiast programmers.

2 Answers 2

find . -type f -name "*.txt" -print0 | xargs -0 gedit

share|improve this answer
    
Thanks. I see that it works. But what does the -print0 | xargs -0 part means? –  xyz Mar 14 '13 at 21:19
    
@xyz, you can read about the flags of any UNIX command using the man pages. Try man find or man xargs, then / to search for a given flag. The documentation is quite good, it should answer your questions. –  David Cain Mar 14 '13 at 21:21
1  
-print0 prints a NULL character after each entry, -0 expects entries to be separated by NULL character. It is the safest way to handle tricky names. –  Notinlist Mar 14 '13 at 21:22
    
And isn't it a little bit strange that the syntax is not gedit xargs -0 instead of xargs -0 gedit. I see that the former doesn't work, but fail to see why. –  xyz Mar 14 '13 at 21:32
1  
xargs is preferable to -exec for performance reasons since xargs can "batch up" a number of arguments before passing them to gedit. If one needed to run gedit against each file individually, replace '... -print0 | xargs -0 gedit' with '... -print0 | xargs -0 -i gedit {}' xargs is one of those commands like find and screen that you never know how you got along without a year after you learn about it. –  arclight Apr 22 at 12:27

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).

share|improve this answer
    
Thanks. I see that it works. But what does the end ("{}" \:) means? execute list? –  xyz Mar 14 '13 at 21:18
    
The {} stands in for the current file name, and the semicolon is just terminating the command. The backslash and the surrounding quotes are just to prevent shell expansion. –  David Cain Mar 14 '13 at 21:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.