从程序输出评估多个模式并写入模式特定文件

Sar*_*use 5 grep bash text-processing

我有一个输出一些值/数字的脚本,我想将它们分成两个文件。我在看类似的东西:

./runme.sh | grep 'ook' >> ook.out | grep 'eek' >> eek.out
Run Code Online (Sandbox Code Playgroud)

在这种情况下,第二个管道不应采用第一个 grep 的输出,而是采用 runme.sh 的输出。那可能吗?

Nik*_*ley 7

那么你应该为这两种模式做 egrep 。

`/.runme.sh | egrep "ok|eek"

但似乎您需要将每个模式评估输出重定向到它自己的文件,grep 似乎不支持。任何人,如果可能,请纠正我。

编辑:minaev 给出了来自 moreutils 的小便示例,但是如果您的平台上缺少小便,我们仍然可以像这样使用 tee。只是玩过程替换。

./runme.sh |tee >(grep ook > ook.txt) >(grep eek > eek.txt)

例子:

[centos@centos scripts]$ ./runme.sh
eekfarapplebin
keeekmajowrwt
keekookjsfskooeek
ook
[centos@centos scripts]$ ./runme.sh | tee >(grep eek >eek.txt) >(grep ook >ook.txt)
eekfarapplebin
keeekmajowrwt
keekookjsfskooeek
ook
[centos@centos scripts]$ cat eek.txt 
eekfarapplebin
keeekmajowrwt
keekookjsfskooeek
[centos@centos scripts]$ cat ook.txt 
keekookjsfskooeek
ook
[centos@centos scripts]$ 
Run Code Online (Sandbox Code Playgroud)


min*_*aev 7

这是实用程序的完美用例pee

./runme.sh | pee "grep ook >> ook.out" "grep eek >> eek.out"

在 Debian 和衍生产品中,pee可以在moreutils包中找到。


man*_*ork 6

简单的awk替代方案:

./runme.sh | awk '/ook/{print>>"ook.out"}/eek/{print>>"eek.out"}'
Run Code Online (Sandbox Code Playgroud)

只需少量添加,awk代码就可以轻松扩展——只需将数组 r 放入,因为需要许多正则表达式-输出文件对:

./runme.sh | awk 'BEGIN{r["ook"]="ook.out";r["eek"]="eek.out"}{for(i in r)if($0~i)print>>r[i]}'
Run Code Online (Sandbox Code Playgroud)

sed w命令相当于>,遗憾的是无法附加到文件:

./runme.sh | sed -n $'/ook/wook.out\n/eek/week.out'
Run Code Online (Sandbox Code Playgroud)