是否可以传递一个相对较大的字符串,grep
或者它只能接受一个文件?
请注意,我不是谈论将输出通过管道传输到 grep,而是执行以下操作:
grep 'hello' 'hello world'
(这当然行不通,至少不是那样)
答案1
这是有可能的。试试这个:
grep 'hello' <<< 'hello world'
您也可以传递包含字符串的变量:
str='hello world'
grep 'hello' <<< $str
答案2
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
输入包含多行文本的字符串。如果您愿意,甚至可以以交互方式将它们输入到 shell 中。
如果这不能满足您的需求,也许您可以解释一下为什么管道不是一个可接受的解决方案?
答案3
通过管道传输grep
为什么不只是:
echo 'hello world' | grep 'hello'
也可以看看:https://stackoverflow.com/questions/2106526/how-can-i-grep-complex-strings-in-variables