将(大)字符串而不是文件名传递给“ grep”


26

可以将相对较大的字符串传递给grep它还是只能接受一个文件?

请注意,我不是在谈论将输出输出到grep,而是这样做:

grep 'hello' 'hello world'

(当然不起作用,至少不是那样)


也许管道某种文本数据到grep?所以也许类似的东西printf "various\ntext to grep here" | grep "text"会产生“这里的文本到grep”
Alex

Answers:



13

grep没有选项将其命令行参数解释为要搜索的文本。grep字符串的通常方法是将字符串传递到grep的标准输入中:

$ 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.
$

如您在此处看到的,您可以echo包含多行文本的字符串。如果愿意,您甚至可以交互方式将其键入到外壳中。

如果这不能满足您的需求,也许您可​​以解释为什么管道不是可接受的解决方案?


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.