首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用否定排除包含`#`的行

使用否定排除包含`#`的行
EN

Stack Overflow用户
提问于 2018-03-29 03:33:02
回答 2查看 84关注 0票数 1

假设我有这样一个文件:

代码语言:javascript
复制
    $ head -n 15 foo.md
    # User Database
    # 
    # Note that this file is consulted directly only when the system is running
    # in single-user mode.  At other times this information is provided by
    # Open Directory.
    #
    # See the opendirectoryd(8) man page for additional information about
    # Open Directory.
    ##
    nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false
    root:*:0:0:System Administrator:/var/root:/bin/sh
    daemon:*:1:1:System Services:/var/root:/usr/bin/false
    _uucp:*:4:4:Unix to Unix Copy Protocol:/var/spool/uucp:/usr/sbin/uucico
    _taskgated:*:13:13:Task Gate Daemon:/var/empty:/usr/bin/false

我想看看不包括“#”的内容,

它可以通过反转选项来实现,比如

$ grep -v "^#“< foo.md i意图与否定^交替

代码语言:javascript
复制
    $ grep -E "[^#]" < foo.md
    # User Database
    # 
    # Note that this file is consulted directly only when the system is running
    # in single-user mode.  At other times this information is provided by

代码语言:javascript
复制
    $ grep -Eo "[^#]+" < foo.md
     User Database

     Note that this file is consulted directly only when the system is running
     in single-user mode.  At other times this information is provided by
     Open Directory.
     See the opendirectoryd(8) man page for additional information about
     Open Directory.
    nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false

命令没有输出我想要的结果。

如何用否定来解决这样的问题?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-03-29 04:00:26

您的文件在#之前有空格,因此您需要对其进行说明。否定在这里是不必要的,并且使一切变得复杂--尤其是当试图进行逆匹配时,所以不要去理会它。

代码语言:javascript
复制
grep -v "^\s*#" file.txt

输出

代码语言:javascript
复制
nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false
root:*:0:0:System Administrator:/var/root:/bin/sh
daemon:*:1:1:System Services:/var/root:/usr/bin/false
_uucp:*:4:4:Unix to Unix Copy Protocol:/var/spool/uucp:/usr/sbin/uucico
_taskgated:*:13:13:Task Gate Daemon:/var/empty:/usr/bin/false

要得到相反的结果,只需失去反向匹配(-v)选项:

代码语言:javascript
复制
grep "^\s*#" 

输出

代码语言:javascript
复制
# User Database
# 
# Note that this file is consulted directly only when the system is running
# in single-user mode.  At other times this information is provided by
# Open Directory.
#
# See the opendirectoryd(8) man page for additional information about
# Open Directory.
##

使用命令grep -Eo "[^#]+",只告诉grep (-o)与行中没有#的部分匹配,因此显然它将输出除#字符之外的所有内容。

POSIX版

代码语言:javascript
复制
grep '^[[:blank:]]*#'
票数 1
EN

Stack Overflow用户

发布于 2018-03-29 03:47:34

如果我是对的,你希望只有非评论行,最后5行,而不以“#”开头?

对于我来说,在Mac或-v上使用grep ^# "^#“非常好,输出中只有最后5行。

选项-v的意思是反转匹配,字符“^”表示“行的开头”

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49547573

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档