Grep 未知数量的空格(linux)

问题描述 投票:0回答:5

假设您有一个名为 abc.txt 的文件 - 该文件包含 2 行(或通常更多行):

word  -c           (09:35:20)
word     -c        (09:38:49)

如果运行命令

$ grep "word  -c" abc.txt
,您只会得到第一行,因为 1 和 -c 之间的空格数与第二行不匹配。有办法解决这个问题吗?

您不能使用

grep'word1|word2' /path/to/file
,因为单词和 -c 之间的空格不同。

regex grep
5个回答
11
投票

使用

+
正则表达式字符,它将匹配至少一个前面的字符:

grep -E "word +-c" abc.txt

此正则表达式为“匹配‘word’,后跟一个或多个空格,后跟‘-c’。”


3
投票

grep 'word *-c' abc.txt 可以工作。我无法让 grep 'word +-c' abc.txt 工作。


1
投票

您可以将egrep与正则表达式一起使用

egrep "word\s+-c" abc.txt

egrep "word +-c" abc.txt

0
投票

grep 'word \+-c' abc.txt

使用单引号,而不是双引号。 “+”表示“一个或多个前面的表达式,因此可以找到任意数量的空格(除了零)。

这里有一个参考:http://www.gnu.org/software/findutils/manual/html_node/find_html/grep-regular-expression-syntax.html


0
投票
cat /etc/ssh/sshd_config | egrep -v "^[[:space:]]?+#" | grep -v "^$"

这将删除以

#
开头的任何行或
#

之前的任何空格
© www.soinside.com 2019 - 2024. All rights reserved.