是否可以将相对较大的字符串传递给grep或它只能接受一个文件?
请注意,我不是在谈论管道输出到 grep,而是在做类似的事情:
grep 'hello' 'hello world'
Run Code Online (Sandbox Code Playgroud)
(这当然行不通,至少不是那样)
小智 40
这是可能的。尝试这个:
grep 'hello' <<< 'hello world'
Run Code Online (Sandbox Code Playgroud)
您还可以传递一个包含字符串的变量:
str='hello world'
grep 'hello' <<< $str
Run Code Online (Sandbox Code Playgroud)
Ken*_*ter 14
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.
$
Run Code Online (Sandbox Code Playgroud)
正如您在此处看到的,您可以使用echo包含多行文本的字符串。如果您愿意,您甚至可以以交互方式将它们键入到 shell 中。
如果这不能满足您的需求,也许您可以解释为什么管道不是可接受的解决方案?
将其输送到grep
为什么不只是:
echo 'hello world' | grep 'hello'
Run Code Online (Sandbox Code Playgroud)
另请参阅:/sf/ask/147456851/
| 归档时间: |
|
| 查看次数: |
54727 次 |
| 最近记录: |