1

I want this to work:

./search.sh < inputFile.json

and

./search.sh < inputFile2.json

That will output something different depending on the file. I would then like to do this:

(./search.sh < inputFile.json) > results.json

I'm sure that syntax is wrong. Is anyone able to put me in the right direction? I can't find how to do this in my ruby script (I'm using .sh but it's ruby).

2 Answers 2

5

You have multiple options.

Read from stdin

One option is to read from stdin. You can for example do in search.sh

#!/usr/bin/env ruby

input = $stdin.read

puts "here's the input i got:"
puts input

Suppose we have a file foo.txt which looks like this

foo
bar
baz

then you can use it with a unix pipe

~$ ./search.sh < foo.txt
here's the input i got:
foo
bar
baz

which is equivalent to

~$ cat foo.txt | ./search.sh
here's the input i got:
foo
bar
baz

although this is useless use of cat and just meant to serve demonstration purposes. You can not only pipe files but also output from other commands

~$ echo "hello, world!" | ./search.sh
here's the input i got:
hello, world!

if you want to redirect the output to another file, do

~$ ./search.sh < foo.txt > bar.txt
~$ cat bar.txt
here's the input i got:
foo
bar
baz

Read file from Ruby

Another way is to just pass the file name as argument and read the file directly from Ruby:

#!/usr/bin/env ruby

file = ARGV.first
input = File.read(file)

puts "here's the input i got:"
puts input

Usage:

~$ ./search.sh foo.txt
here's the input i got:
asfdg
sdf
sda
f
sdfg
fsd

and again to redirect the output use >

~$ ./search.sh foo.txt > bar.txt
Sign up to request clarification or add additional context in comments.

Comments

2

I'm assuming the content of the input files will be different and you will have some logic to determine that. You can actually just read that file input as if it was entered as text by the user and do whatever you need to do with it.

Example:

test.rb

puts gets.chomp

testfile

test

Terminal

$ ruby test.rb < testfile
$ test

2 Comments

That makes so much sense. I was using gets.chomp but didn't realize if you feed it a file, it will complete the gets.chomp immediately. (Usually I use gets.chomp when prompting users for input. Thanks so much this helped a ton!
@p11y The chomp is not necessary and is dependant on what you want to do with the input, I was just trying to show that it can be used as text normally entered into a program.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.