Launch an editor with a list of files containing a string

This one’s here for my own reference as much as anything, because I will want to do this again and I’d rather not have to go dig it up.

If you want to launch an editor with a list of files matching a specific pattern from any Unix or Linux terminal, the quickest and simplest way I’ve found to do it as follows:

find directory [-name modifiers] -exec grep -l pattern | xargs editor

So, for example, I just wanted to use Sublime Text 2 open every Fortran 95 file in a directory that writes to disk, so I ran the following:

find . -name "*.f95" -exec grep -l 'write(' {} + | xargs subl

For folks relatively new to the command line, I’ll break that down:


find . -name "*.f95" -exec ... {} + launches the find program, tells it start in the current directory (.) and to find all files with a name ending in .f95. It then uses the results as the basis for the next command with the -exec flag—you could also use xargs as we will later, but it’s not safe to do so unless you know the file won’t have any spaces in it. The {} + actually passes the results of the find command as the arguments to the command specified by -exec, in this case grep.


grep -l 'write(' searches through a set of files—in this case, those handed to the command by find looking for the pattern write(. The -l flag indicates that the files should simply be listed, instead of the normal behavior, which is printing the actual contents of the line where the text was found to the screen.


xargs takes the list of files generated by the grep command and uses them as arguments to the next command. This is safe (unlike doing the same would be for find) because grep -l returns its file list with directory structures attached (e.g. ./myfile.f95), so there’s no ambiguity as to how space or tab characters in the name should be interpreted.


subl is just the command line string to launch the Sublime Text editor; it takes file names as arguments, which is why it works this way. (Most sensibly written text-editing apps do; even my new favorite writing application Byword can be launched from the OS X command line with the command open -a and will take file names as arguments.) You could just as easily do this with old standby editors like vim or Emacs.

Pipe up!

Anonymity is most unhelpful. Please identify yourself!

You may use GitHub-flavored Markdown and/or these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>