我需要查找文件中是否有任何行以**
.
我不知道如何做到这一点,因为*
它被 shell 解释为通配符。
grep -i "^2" test.out
如果该行以 2 开头,则有效,但是
grep -i "^**" test.out
显然不起作用。
(我还需要知道该行是否以 a 结尾,)
但尚未尝试)。
答案1
使用该\
字符对 * 进行转义,使其成为普通字符。
grep '^\*\*' test.out
另请注意单引号'
而不是双引号,"
以防止 shell 扩展内容
答案2
**
当您想检查以 开头和结尾的行时)
,您可以组合两个grep
操作,如下所示,
grep '^*\*' test.out | grep ')$'
或者使用grep
这样的单个命令,
grep -E '^\*\*.*\)$' test.out
解释
^\*\*
: match line which starts with**
.*
: match everything after**
\)$
: match line which also has)
at the end of line.
答案3
It's not the shell
None of the answers so far has touched on the real problem. It would be helpful to explain why it does not work as you expect.
grep -i "^**" test.out
Because you have quoted the pattern to grep, *
is not expanded by the shell. It is passed to grep as-is. This is explained in the manual page[1] for bash[2]:
Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !.
It's regular ordinary regular expressions
A regular expression is a pattern that describes a set of strings.
*
is one of the key patterns in regular expressions. By default, grep interprets it as follows:
* The preceding item will be matched zero or more times.
This means that your pattern as it stands, ^**
does not make much sense. Possibly it tries to match the beginning of the line zero or more times, twice. Whatever that means.
The solution is to quote it:
Any meta-character with special meaning may be quoted by preceding it with a backslash.
grep -i "^\*\*" test.out
[1] I do not recommend reading it. Please use man dash
or similar instead.
[2] No shell was given, so I assume bash.
答案4
这是完全未引用的版本:grep ^\\*\\* test.out
。要将文字反斜杠从 shell 传递到 grep,需要对其进行转义。
只要目录中没有以另一个反斜杠开头^\
并包含另一个反斜杠的文件,此操作就有效。