我使用下面的命令来过滤文件中的 # 和空行。但是,我们如何使用单个 grep 在 Linux 中 grep 未注释的行和空行。
[root@localhost ~]# cat test | grep -v ^# | grep -v ^$
Run Code Online (Sandbox Code Playgroud)
对于简单的情况,我的首选模式是:
$ egrep '^[^#]'
Run Code Online (Sandbox Code Playgroud)
此模式匹配以井号以外的某些字符开头的行。
如果您扩展“空白”行的定义以包含完全由空格组成的行,则该模式将失败,因为它将匹配这样的行。如果您在注释行中的井号之前允许任意空格(如 Apache、bash 和其他语言所做的那样),该模式也会失败。
如果这些案例对您很重要,那么这种模式更好:
$ egrep '^[[:blank:]]*[^[:blank:]#]'
Run Code Online (Sandbox Code Playgroud)
例如:
$ cat test
# comment
# spaces then comment
config # then comment
before empty line
after empty line
space only on next line
tab only on next line
$ egrep '^[[:blank:]]*[^[:blank:]#]' test
config # then comment
before empty line
after empty line
space only on next line
tab only on next line
$
Run Code Online (Sandbox Code Playgroud)