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:
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
Here's sample output on my Mac:
Searching *.rb for "puts"... ./finder.rb:4:puts ./finder.rb:5:puts ./finder.rb:11:puts ./finder.rb:22:puts
And here's some sample output from a Linux machine:
Searching *.c for "struct task_struct"... ./fs/fcntl.c:414:struct task_struct ./fs/fcntl.c:423:struct task_struct ./fs/fcntl.c:462:struct task_struct ./fs/fcntl.c:481:struct task_struct ./fs/fcntl.c:490:struct task_struct