28

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)

  • Maybe pipe some kind of text data to grep? So maybe something like printf "various\ntext to grep here" | grep "text" will produce "text to grep here" – Alex May 2 '14 at 3:12
33

It's possible. Try this:

grep 'hello' <<< 'hello world'

You can also pass a variable containing string instead:

str='hello world'
grep 'hello' <<< $str
| improve this answer | |
  • 5
    For reference, this is a here string. You can read more here. – Rockallite Feb 7 '17 at 6:39
  • 1
    quote from wiki: available in bash, ksh, or zsh – hoijui Jul 16 '19 at 5:22
13

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?

| improve this answer | |
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

| improve this answer | |

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.