Pass a (large) string to 'grep' instead of a file name

Is it possible to pass a relatively large string to grep or can it only accept a file?

Note that I'm not talking about piping output to grep, but doing something like:

grep 'hello' 'hello world'

(which of course doesn't work, at least not like that)

1

3 Answers

It's possible. Try this:

grep 'hello' <<< 'hello world'

You can also pass a variable containing string instead:

str='hello world'
grep 'hello' <<< $str
2

grep doesn't have an option to interpret its command-line arguments as text to be searched. The normal way to grep a string is to pipe the string into grep's standard input:

$ echo 'There once was a man from Nantucket
Who kept all his cash in a bucket. But his daughter, named Nan, Ran away with a man
And as for the bucket, Nantucket.' | grep -i nan
There once was a man from Nantucket But his daughter, named Nan,
And as for the bucket, Nantucket.
$

As you see here, you can echo strings containing more than one line of text. You can even type them into the shell interactively, if you like.

If this doesn't meet your needs, maybe you could explain why piping isn't an acceptable solution?

Pipe it into grep

Why not just:

echo 'hello world' | grep 'hello'

See also:

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like