regex - 如何在 grep 的输出前加上标签?

标签 regex linux unix command-line grep

假设我有以下文本:

name is test1 and age is test2 end
name is test3 and age is test4 end
name is test5 and age is test6 end
name is test7 and age is test8 end

我正在 grepping 测试 1、测试 2、...,如下所示:

-bash$ grep -o -P "is .*? and|is .*? end" test
is test1 and
is test2 end
is test3 and
is test4 end
is test5 and
is test6 end
is test7 and
is test8 end

有没有办法在匹配的模式前添加一些文本?我正在寻找这样的输出:

STRING1:is test1 and
STRING2:is test2 end
STRING1:is test3 and
STRING2:is test4 end
STRING1:is test5 and
STRING2:is test6 end
STRING1:is test7 and
STRING2:is test8 end

最佳答案

我将 grep 的输出通过管道传输到 awk 以满足您的需要:

grep -o -P "is .*? and|is .*? end" test | \
awk -v a=STRING1: -v b=STRING2: "/and$/ {print a\$0} /end$/ {print b\$0}"

关于regex - 如何在 grep 的输出前加上标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10468988/

相关文章:

unix - 使用 awk 从 fasta 文件中选择一组序列的问题

c - 多个线程如何拥有相同的线程ID?

regex - vi:::s 如何只替换一行中的第二次出现?

正则表达式具有可选参数的多个 URL,一些需要反向引用,一些不需要

linux - 使用 grep、sed 或 awk 解析字符串

linux - 当我们运行一个可执行文件时,是否所有的部分都被一次加载到内存中?

regex - Emacs 删除字符串中的最后一个目录

c - 匹配不在引号内的模式

linux - 如何在RHEL Azure VM上的/mnt/resource中创建目录

c - 在这种情况下,SIGCHILD信号将如何处理?