使用正则表达式解析文件时,匹配一行直到 # ,但没有 #

stw*_*sel 3 debian bash regex

我想解析 mysources.list以提取存储库列表。我有:

## Some comment
deb http://some.vendor.com/ubuntu precise stable
deb-src http://some.vendor.com/ubuntu precise stable
deb http://some.othervendor.com/ubuntu precise experimental # my current favorite
Run Code Online (Sandbox Code Playgroud)

我想要:

http://some.vendor.com/ubuntu precise stable
http://some.othervendor.com/ubuntu precise experimental
Run Code Online (Sandbox Code Playgroud)

所以我需要: 只在行首到行尾或一个#字符带有“deb”的行,但不包括它。到目前为止,我有:

grep -o "^deb .*"
Run Code Online (Sandbox Code Playgroud)

但是如何在#不匹配 的情况下匹配或结束行#

小智 7

使用grep

grep -Po '(?<=^deb\s).*?(?=#|$)' inputFiles 
Run Code Online (Sandbox Code Playgroud)

根据@kopischke 的建议

grep -Po '(?<=^deb\s)[^#]*' inputFiles
Run Code Online (Sandbox Code Playgroud)

使用sed

sed -nr '/^deb\s/s;^deb\s([^#]*)#?.*$;\1;p' inputFiles
Run Code Online (Sandbox Code Playgroud)

使用awk(此解决方案基于固定字段的数量):

awk '/^deb /{print $2,$3,$4}' inputFiles
Run Code Online (Sandbox Code Playgroud)

  • +1 为 `grep` Perl 正则表达式(从来没有注意到那个,猜“Perl”让我跳过它:))。但是,您不需要先行来排除哈希——一个否定的字符类,即`[^#]*`,就可以了(行尾不需要明确匹配——无论如何 grep 匹配行)。 (2认同)