Search code examples
rubybashgrepbackticks

Ruby, using backticks to grep file extensions and searching file content for a string


I'm trying to locate txt and html files that contains "some string user input" in their contents.

in the command line the following command works perfect.

grep -ri --include \*.txt --include \*.html string .

but when trying to code it into ruby program as following:

s = ARGV[0]
files = %x(grep -ri --include \*.txt --include \*.html #{s} .) 

and this is how I run my program

$ ruby app.rb string

it doesn't work.

any ideas on how to get it to work that way?

thanks in advance


Solution

  • \ escapes * in Ruby, which does not need to be escaped, so the text transmitted to the shell is grep -ri --include *.txt --include *.html filename .. Escape the backslash so that shell gets it intact:

    files = %x(grep -ri --include \\*.txt --include \\*.html #{s} .)