2017-04-12 24 views
0

我有一些传统的bash代码,我正在运行并且想要插入应该转到标准输出的打印语句。我想将有去标准输出去out.out和任何将有去stderr去err.err基于内容将输出重定向到3个不同的文件

运行myCode.sh 2> err.err 1> out.out将打印出来一切正常,但我想放像echo "NewStatement: I am at this point in the code"打印报表,然后以某种方式预grep命令NewStatement并将其发送到标准输出,而其他一切正常得到处理。

在本质上我想:

1)在含有NewStatementstdoutstdout含有NewStatement发送任何东西stdout

2)发送什么out.out

3)发送任何东西在stderrerr.err

这可能吗?

回答

0

这很容易。首先,“初学者”解决方案。

创建wrapper脚本(或包装功能的主脚本),这将包含这样的事情:

#!/bin/bash 

while read line || [[ $line ]] 
do 
    if 
    [[ $line =~ NewStatement ]] 
    then 
    echo "$line" 
    else 
    echo "$line" >> out.out 
    fi 
done< <("[email protected]" 2>err.err) 

然后,只需打电话给你这样的脚本(假设一切都是可执行文件,在当前目录:

./wrapper myCode.sh 

模式“先进”的解决方案使用文件描述符打开目标文件进行写入。

#!/bin/bash 

exec 3> out.out # Open file descriptor 3 for writing to file 

while read line || [[ $line ]] 
do 
    if 
    [[ $line =~ NewStatement ]] 
    then 
    echo "$line" 
    else 
    echo "$line" >> &3 
    fi 
done< <("[email protected]" 2>err.err) 

exec 3>&- # Close file descriptor 

您可以有许多文件描述符根据任意复杂的条件执行输出到许多单独的文件。

1

你可以这样说:

>out.out 

./myCode.sh 2> err.err 1> >(awk '!/^NewStatement/{print > "out.out"; next} 1') 

awk命令内部进程替换打印到out.out如果行不NewStatement启动。否则,以NewStatement开头的行将打印到stdout

1

或者,您可以

myCode.sh 2>err.err | tee >(grep -v NewStatement > out.out) | grep NewStatement 

tee从他stdin复制一切,所以

  • 发球-ED流由grep -v patt过滤(如不含)和重定向
  • stdout if if grep patt(eg仅包含当线)

这可以重复任何次,像

cmd | tee >(cmd1) >(cmd2) >(cmd3) | cmd 
相关问题