假设我有这样一个文件:
$ 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意图与否定^交替
$ 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和
$ 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命令没有输出我想要的结果。
如何用否定来解决这样的问题?
发布于 2018-03-29 04:00:26
您的文件在#之前有空格,因此您需要对其进行说明。否定在这里是不必要的,并且使一切变得复杂--尤其是当试图进行逆匹配时,所以不要去理会它。
grep -v "^\s*#" file.txt输出
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)选项:
grep "^\s*#" 输出
# 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版
grep '^[[:blank:]]*#'发布于 2018-03-29 03:47:34
如果我是对的,你希望只有非评论行,最后5行,而不以“#”开头?
对于我来说,在Mac或-v上使用grep ^# "^#“非常好,输出中只有最后5行。
选项-v的意思是反转匹配,字符“^”表示“行的开头”
https://stackoverflow.com/questions/49547573
复制相似问题