Open all files containing a pattern

To search the current directory for all files called [filename] (a regexp) that contain the given [pattern] (a regexp) and open them in [program]:

find . -name "[filename]" -exec grep "[pattern]" -ls {} \; | xargs [program]

For example, this will open all ruby files in gvim if they contain the word "logger".

find . -name "*.rb" -exec grep "logger" -ls {} \; | xargs gvim --remote-tab-silent

How we got there...

Search for files

To search a directory for all files of a given filename:

find [directory] -name "[filename]"

E.g. search the current directory for all files with an .rb extension (ruby files):

find . -name "*.rb"

Find text in a file

To search [filename] for a [pattern]:

grep [pattern] [filename]

E.g. search hello.rb for the words "puts 'hi'":

grep "puts 'hi'" hello.rb

Open multiple files in a program

To pass each line returned by a [command] to a [program]:

[command] | xargs [program]

E.g. To cat each file listed by 'ls -C1':

ls -C1 | xargs cat

Last modified: 23/09/2008 Tags: (none)

This website is a personal resource. Nothing here is guaranteed correct or complete, so use at your own risk and try not to delete the Internet. -Stephan

Site Info

Privacy policy

Go to top