简体   繁体   中英

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

\\ 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} .) 
#!/bin/env ruby
# encoding: utf-8
s = ARGV[0]
files = %x|grep -ri --include \*.txt --include \*.html #{s} .| 
puts files

you could use | instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM