2

I want to run the following grep from within a Ruby script:

grep "word1" file1.json | grep -c "word2"

This will find the number of lines in the file with both words appearing. I could do this with Ruby regex, but it seems that Unix grep is much faster. So my question is how do I run this command within a script and return the result back to a Ruby variable?

I'd love to hear alternative solutions that don't use grep, if they are as fast or even faster.

Evan Zamir
  • 8,059
  • 14
  • 56
  • 83
  • possible duplicate of [Calling Bash Commands From Ruby](http://stackoverflow.com/questions/2232/calling-bash-commands-from-ruby) – mechanicalfish Nov 01 '13 at 17:02

1 Answers1

4

Use backticks to execute shell commands:

result = `grep "word1" file1.json | grep -c "word2"`
tckmn
  • 57,719
  • 27
  • 114
  • 156
  • Wow, I didn't realize it was so easy. Learn something new every day! Thanks. – Evan Zamir Nov 01 '13 at 17:29
  • There are actually multiple ways to execute shell commands in ruby, each with slightly different properties. [Here's a good article](http://tech.natemurray.com/2007/03/ruby-shell-commands.html) about the differences. – Matt Sanders Nov 01 '13 at 17:48
  • @MattSanders Fantastic! Is that pretty much current still? – Evan Zamir Nov 01 '13 at 18:07
  • Seems like there are many ways, but some are better than others. I recommend reading [this answer](https://stackoverflow.com/a/24545829/532517) and [short article](https://www.honeybadger.io/blog/capturing-stdout-stderr-from-shell-commands-via-ruby/) – H.Wolper Dec 28 '21 at 07:32