Bash 使用grep过滤线流并用检测到的模式为其添加前缀
遇到了一个棘手的问题,即使用grep过滤多个模式,同时根据所选模式修改流本身 如果我想过滤多个模式的let,比如“ps-ef”输出,我可以这样做Bash 使用grep过滤线流并用检测到的模式为其添加前缀,bash,awk,sed,grep,stream-processing,Bash,Awk,Sed,Grep,Stream Processing,遇到了一个棘手的问题,即使用grep过滤多个模式,同时根据所选模式修改流本身 如果我想过滤多个模式的let,比如“ps-ef”输出,我可以这样做 ps -ef |grep -E "client|postgres:" postgres 142705 3845 0 12:04 ? 00:00:00 postgres: suiteadmin suiteadmin 127.0.0.1(34380) idle postgres 142979 3845 3 12:04 ?
ps -ef |grep -E "client|postgres:"
postgres 142705 3845 0 12:04 ? 00:00:00 postgres: suiteadmin suiteadmin 127.0.0.1(34380) idle
postgres 142979 3845 3 12:04 ? 00:00:00 postgres: cost securetrack [local] idle
postgres 142989 3845 12 12:04 ? 00:00:00 postgres: cost securetrack [local] SELECT
root 142991 140798 0 12:04 pts/0 00:00:00 my.client -fce
然而,我无法在流处理的后期判断“客户机”或“postgres:”模式是否与特定的流行匹配(这对我的用例至关重要)
如果我选择使用-o参数,grep将从我请求的多个模式中提供实际匹配的模式,但它不会打印整个流行
它在中找到了模式(我也需要)
我希望grep(或者其他工具)给我“匹配模式”+“带有匹配模式的行”,这样我可以在以后将其作为一个流进行处理,知道它在第一时间被选中的原因
我不太确定我能和grep一起做
有没有其他工具我可以用来做这个?(awk、sed等)
对我来说,快速高效地完成这项工作是很重要的,所以我不想一开始就把循环和对不同linux可执行工具的多次调用搞得一团糟
希望使用一个工具将其作为流进行处理,该工具既可以通过多个选项进行过滤,也可以告诉我它是通过哪种模式选择的,我想这就是您要寻找的:
$ ps -ef | sed -nE 's/.*(client|postgres:).*/\1 &/p'
postgres: postgres 142705 3845 0 12:04 ? 00:00:00 postgres: suiteadmin suiteadmin 127.0.0.1(34380) idle
postgres: postgres 142979 3845 3 12:04 ? 00:00:00 postgres: cost securetrack [local] idle
postgres: postgres 142989 3845 12 12:04 ? 00:00:00 postgres: cost securetrack [local] SELECT
client root 142991 140798 0 12:04 pts/0 00:00:00 my.client -fce
这将捕获匹配的字符串并将其添加到匹配行的开头您可以使用
awk
来执行以下操作:
ps -ef |
awk -v kw='client;postgres:' 'BEGIN{n=split(kw, a, /;/)} {
for (i=1; i<=n; i++) if ($0 ~ a[i]) print a[i] "#", $0}'
- 使用
我们通过了一个-v kw='client;博士后:“
代码>要在
输出中搜索的分隔关键字ps
- 使用
函数,我们将列表拆分为一个数组split
a
- 在主块中,我们检查一行是否包含任何关键字,然后使用该关键字作为该行的前缀
- 另一个awk:
$ echo foo bar |
awk -v s="bar|baz" '$0~s{match($0,s);print substr($0,RSTART, RLENGTH) ":", $0}'
bar: foo bar
在
s
变量中给出搜索模式。它只支持行中的第一个匹配项,但很容易扩展以显示所有匹配项。请添加预期输出以澄清您的需求…效果良好。正是我需要的。有一种感觉,awk可以做到这一点。但是我几乎不知道除了常规的打印这个和,平均那个曼波巨无霸之外的语法。非常感谢,我很高兴知道它成功了,
postgres:# postgres 142705 3845 0 12:04 ? 00:00:00 postgres: suiteadmin suiteadmin 127.0.0.1(34380) idle
postgres:# postgres 142979 3845 3 12:04 ? 00:00:00 postgres: cost securetrack [local] idle
postgres:# postgres 142989 3845 12 12:04 ? 00:00:00 postgres: cost securetrack [local] SELECT
client# root 142991 140798 0 12:04 pts/0 00:00:00 my.client -fce
$ echo foo bar |
awk -v s="bar|baz" '$0~s{match($0,s);print substr($0,RSTART, RLENGTH) ":", $0}'
bar: foo bar