Regex 如何搜索整行
我的目的是确定配置文件中是否存在整行。 以下是一个例子: ports.conf:Regex 如何搜索整行,regex,linux,unix,grep,escaping,Regex,Linux,Unix,Grep,Escaping,我的目的是确定配置文件中是否存在整行。 以下是一个例子: ports.conf: #NameVirtualHost *:80 NameVirtualHost *:80 现在我想搜索NameVirtualHost*:80,但不想搜索#NameVirtualHost*:80 当然,我的第一个想法是使用grep。像这样: grep-F“NameVirtualHost*:80”ports.conf这两行代码都是而不是我想要的。 我的第二个想法是像这样使用正则表达式:grep-e“^NameVirtua
#NameVirtualHost *:80
NameVirtualHost *:80
现在我想搜索NameVirtualHost*:80
,但不想搜索#NameVirtualHost*:80
当然,我的第一个想法是使用grep。像这样:
grep-F“NameVirtualHost*:80”ports.conf
这两行代码都是而不是我想要的。
我的第二个想法是像这样使用正则表达式:grep-e“^NameVirtualHost\*:80”ports.conf
。但显然现在我必须处理转义特殊字符行*
这可能没什么大不了的,但我想传入单个搜索字符串,不想在使用脚本时麻烦转义字符串
所以我的问题是:
如何转义特殊字符?或如何使用不同的工具实现相同的结果?
grep
有一个选项-x
,该选项正好执行以下操作:
-x, --line-regexp
Select only those matches that exactly match the whole line. (-x is specified by POSIX.)
因此,如果您将第一个命令更改为
grep-Fx“NameVirtualHost*:80”ports.conf
,您将得到所需的内容。grep
有一个选项-x
,该选项正好执行以下操作:
-x, --line-regexp
Select only those matches that exactly match the whole line. (-x is specified by POSIX.)
因此,如果您将第一个命令更改为
grep-Fx“NameVirtualHost*:80”ports.conf
,您将得到您想要的。我能想到的保持regexp简单的最快方法是
grep -F "NameVirtualHost *:80" ports.conf | grep -v "^#\|^\/\/"
我能想到的保持regexp简单的最快方法是
grep -F "NameVirtualHost *:80" ports.conf | grep -v "^#\|^\/\/"
使用printf转义
printf '%q' 'NameVirtualHost *:80'
全部
grep -e "^`printf '%q' 'NameVirtualHost *:80'`$" test
或
使用printf转义
printf '%q' 'NameVirtualHost *:80'
全部
grep -e "^`printf '%q' 'NameVirtualHost *:80'`$" test
或
很好地使用了
-x
。但是如果该行有前导空格(制表符或空格),该怎么办(空格…)NameVir…
?很好地使用了-x
。但是如果该行有前导空格(制表符或空格),该怎么办<代码>(空格…)NameVir…?对我没有帮助。如果有一个注释行是用/
而不是
表示的,那么它就被破坏了。没错,如果在#前面有空格,比如` ` ` ` ` NameVirtualHost*:80`或者在后面有一个注释,比如NameVirtualHost*:80`,这也没有帮助。如果注释行中有/
而不是
,则该行将被破坏。如果在#之前有空格,如`#NameVirtualHost*:80`或在NameVirtualHost*:80#comment
之后有注释,则该行也将无效。