我正在尝试编写一个正则表达式 (e)grep
命令,该命令将打印 txt 文件中的所有行,但忽略以空格开头的行(手动缩进文件)。我无法弄清楚如何一起使用行开头 ^
和排除 ^
。谢谢!
最佳答案
实现此目的的一个好方法是使用 negated character class 。
就像[abc]
将匹配a
、b
或c
、[^ abc]
将匹配除 a
、b
或 c
之外的任何字符。 ^
将正则表达式锚定在行的开头,因此它后面的内容必须匹配字符串的第一个字符。
$ cat test
does not start with space
starts with space
starts with more spaces
another good line
$ egrep '^[^ ]' test
does not start with space
another good line
如果我们想跳过以空格开头的行,包括制表符,可以在字符类中使用特殊的 [:space:]
括号表达式:
egrep '^[^[:space:]]' test
如果您不想在行中查找其他内容,您还可以使用反向匹配:
-v, --invert-match
Selected lines are those not matching any of the specified pat-
terns.
所以我们可以这样做:
egrep -v '^[[:space:]]' test
grep
也应该这样做:
grep -v '^[[:space:]]' test
关于regex - 从egrep打印输出中排除以空格开头的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35384642/