Tom*_*ley 30 grep regular-expression
我想为\resources\
. 我该怎么做呢?
我试过了:
grep \resources\
grep \\resources\\
grep "\resources\"
grep "\\resources\\"
Run Code Online (Sandbox Code Playgroud)
Sté*_*nez 32
反斜杠是许多应用程序的特殊字符:
包括外壳:您需要使用另一个反斜杠或更优雅地将其转义,尽可能使用单引号:
$ printf '%s\n' foo\\bar 'foo\bar'
foo\bar
foo\bar
Run Code Online (Sandbox Code Playgroud)
这里命令接收到两个带有 value 的参数foo\bar
,它们在终端上按原样回显。
(在上面,我使用printf
而不是echo
尽可能多的echo
实现也对反斜杠进行自己的解释(这里将扩展\b
为退格字符))。
但反斜杠也是grep
. 此命令可识别许多特殊序列,如\(
、\|
、\.
等。因此,类似地,您需要\\
为实际的反斜杠字符提供双精度值的 grep 。这意味着使用 shell 需要键入:
grep 'foo\\bar'
Run Code Online (Sandbox Code Playgroud)
或等效地:
grep foo\\\\bar
Run Code Online (Sandbox Code Playgroud)
(这两行都告诉 shellfoo\\bar
作为参数传输到grep
)。
许多其他命令在它们的一些参数中解释反斜杠……并且需要两级转义(一个是为了逃避 shell 解释,一个是为了逃避命令解释)。
顺便说一下,对于 shell,单引号可以'…'
防止任何类型的字符解释,但双引号只能防止其中的一些:特别是$
,`
并\
在"…"
.
mil*_*013 25
您也可以使用fgrep
(仅grep
与-F
标志一起使用)。这会强制 grep 将模式解释为固定字符串(即将 a\
视为文字\
)。您仍然需要保护反斜杠免受 shell 的扩展。
grep -F '\resources\'
Run Code Online (Sandbox Code Playgroud)
grep
需要四个反斜杠来表示一个反斜杠:
grep "\\\\resources\\\\"
Run Code Online (Sandbox Code Playgroud)