sed - sed:如何打印每行中的所有匹配项?
问题描述
我有一个两行字符串:
> a="Microarchitectural Data Sampling (MDS) aka CVE-2018-12126, CVE-2018-12127,CVE-2018-12130, CVE-2019-11091, publicly announced by Intel on 5/14/2019, this has high visibility and lots of public media exposure.\nMicroarchitectural Data Sampling (MDS) aka CVE-2018-12126, CVE-2018-12127,CVE-2018-12130, CVE-2019-11091, publicly announced by Intel on 5/14/2019, this has high visibility and lots of public media exposure."
> echo -e $a
Microarchitectural Data Sampling (MDS) aka CVE-2018-12126, CVE-2018-12127,CVE-2018-12130, CVE-2019-11091, publicly announced by Intel on 5/14/2019, this has high visibility and lots of public media exposure.
Microarchitectural Data Sampling (MDS) aka CVE-2018-12126, CVE-2018-12127,CVE-2018-12130, CVE-2019-11091, publicly announced by Intel on 5/14/2019, this has high visibility and lots of public media exposure.
我要打印的是:
CVE-2018-12126 CVE-2018-12127 CVE-2018-12130 CVE-2019-11091
CVE-2018-12126 CVE-2018-12127 CVE-2018-12130 CVE-2019-11091
# OR
CVE-2018-12126
CVE-2018-12127
CVE-2018-12130
CVE-2019-11091
CVE-2018-12126
CVE-2018-12127
CVE-2018-12130
CVE-2019-11091
我在下面尝试过:
> echo -e $a | sed -r 's/.*(CVE-[0-9]{4}-[0-9]{4,6}).*/\1/g'
CVE-2019-11091
CVE-2019-11091
它只打印每行的最后一个匹配项:-)
如何打印所有匹配的组?
解决方案
grep
与-o
仅输出匹配子字符串的选项一起使用:
grep -o 'CVE-[0-9]\{4\}-[0-9]\{4,6\}' file > outputfile
请注意,其中的大括号\{4\}
被转义,因为这是默认的 POSIX BRE 引擎兼容正则表达式。
使用sed,简单的解决方案是使用两个步骤:用换行符包装预期的匹配项,然后提取与您的模式完全匹配的那些:
pat='CVE-[0-9]\{4\}-[0-9]\{4,6\}'
sed "s/$pat/\n&\n/g" file.txt | sed -n "/^$pat\$/p" > outputfile
输出:
CVE-2018-12126
CVE-2018-12127
CVE-2018-12130
CVE-2019-11091
CVE-2018-12126
CVE-2018-12127
CVE-2018-12130
CVE-2019-11091
查看在线演示