For my Linux kernel class, I often know that some struct exists somewhere, or remember seeing a macro defined in some file and it might be useful, but I can’t remember where I saw something. I also end up trying to track down all the places a particular function is called, and don’t want grep to go digging through every… single… file in the entire kernel directory structure when I only care about .c files. So, I dug up a lengthy combination of file and grep that limits grep’s searching to particular files. I’m lazy about remembering this and retyping it on different computers, too, though, so I wrote a quick Ruby script to do it for me:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/ruby

unless ARGV.length >= 2
  puts "Usage:  #$0 file_extension query"
  puts "\tExample: #$0 '*.h' 'struct list_head'"
  exit
end

unless ARGV.length == 2
  extra_args = ARGV[2...ARGV.length].join ', '
  puts "Warning:  extra arguments ignored: " << extra_args
end

file_extension = ARGV[0]
query = ARGV[1]
command = "find . -type f -name '#{file_extension}' -print0 | xargs -0 grep --line-number --color -H -o '#{query}'"
system 'clear'
puts "Searching #{file_extension} for \"#{query}\"..."
system command

Sample output:

Searching *.rb for "puts"...
./finder.rb:4:puts
./finder.rb:5:puts
./finder.rb:11:puts
./finder.rb:22:puts