【问题标题】:Redirect output to 3 different files based on content根据内容将输出重定向到 3 个不同的文件
【发布时间】:2017-04-12 19:22:32
【问题描述】:

我有一些遗留的bash 代码正在运行,并且想要插入应该进入标准输出的打印语句。我希望 本来可以 发送到 stdout 的任何东西都发送到 out.out,而 本来可以 发送到 stderr 的任何东西都发送到 err.err

运行myCode.sh 2> err.err 1> out.out 将正常打印所有内容,但我想输入echo "NewStatement: I am at this point in the code" 之类的打印语句,然后以某种方式对NewStatement 进行预grep 并将其发送到stdout,而其他所有内容都被视为正常。

本质上我想:

1) 将stdout 中包含NewStatement 的任何内容发送至stdout

2) 将stdout 中包含NewStatement 的任何内容发送到out.out

3) 将stderr 中的任何内容发送至err.err

这可能吗?

【问题讨论】:

    标签: linux bash pipe stdout


    【解决方案1】:

    你可以这样做:

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

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

    【讨论】:

      【解决方案2】:

      你也可以

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

      tee 复制了他的stdin 中的所有内容,所以

      • tee-ed 流被grep -v patt 过滤(例如不包含)并重定向
      • stdout 如果被grep patt 过滤(例如,只有包含时的行)

      这可以重复任何时间,比如

      cmd | tee >(cmd1) >(cmd2) >(cmd3) | cmd
      

      【讨论】:

        【解决方案3】:

        这很容易。一、“初学者”解决方案。

        创建一个wrapper 脚本(或主脚本中的包装函数),其中包含以下内容:

        #!/bin/bash
        
        while read line || [[ $line ]]
        do
          if
            [[ $line =~ NewStatement ]]
          then
            echo "$line"
          else
            echo "$line" >> out.out
          fi
        done< <("$@" 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< <("$@" 2>err.err)
        
        exec 3>&- # Close file descriptor
        

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-08-09
          • 1970-01-01
          • 2023-03-21
          • 2015-07-06
          • 2017-12-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-31
          相关资源
          最近更新 更多