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

Solution 1:

It's possible. Try this:

grep 'hello' <<< 'hello world'

You can also pass a variable containing string instead:

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

Solution 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?

Solution 3:

Pipe it into grep

Why not just:

echo 'hello world' | grep 'hello'

See also: https://stackoverflow.com/questions/2106526/how-can-i-grep-complex-strings-in-variables