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

27

9

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)

user2018084

Posted 2014-05-02T03:04:05.320

Reputation: 1 604

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 – 2014-05-02T03:12:39.933

Answers

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

Kiki Luqman Hakiem

Posted 2014-05-02T03:04:05.320

Reputation: 431

5

For reference, this is a here string. You can read more here.

– Rockallite – 2017-02-07T06:39:46.170

1quote from wiki: *available in bash, ksh, or zsh* – hoijui – 2019-07-16T05:22:25.523

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?

Kenster

Posted 2014-05-02T03:04:05.320

Reputation: 5 474

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

Ciro Santilli 新疆改造中心法轮功六四事件

Posted 2014-05-02T03:04:05.320

Reputation: 5 621