【问题标题】:Write stdout to two different files (one overwrite, one append) in bash在 bash 中将标准输出写入两个不同的文件(一个覆盖,一个附加)
【发布时间】:2014-07-31 19:37:27
【问题描述】:

我有一堆由groupnumber 组织的实验。我有 3 个不同的 groupsnumber,我希望运行 2 个不同的实验。换句话说,我有以下实验要运行:

group A, 1
group A, 2
group B, 1
group B, 2
group C, 1
group C, 2

每次我运行一个将实验结果打印到标准输出的程序时,我都希望将这些结果放入一个文本文件中。我想要一个单独的文本文件用于每个 groupnumber 组合的结果,还需要一个单独的文本文件用于每个包含所有 number 运行的 group 的结果。

所以,这是我运行所有这些实验的 bash 脚本:

#!/bin/bash

groups="A B C"
numbers="1 2"

rm *.txt

for g in $groups; do

    # Set the group settings based on the value of $g

    for n in $numbers; do

        # Set the number settings based on the value of $n

        ./myprogram >> $g-results.txt

    done

done

使用上面的代码,我最终得到了这些文本文件:

A-results.txt
B-results.txt
C-results.txt

但我也想要文本文件:

A-1-results.txt
A-2-results.txt
B-1-results.txt    
B-2-results.txt
C-1-results.txt
C-2-results.txt

如何更改我的 ./myprogram... 命令,以便将输出连接 (>>) 到一个文本文件(就像我已经在做的那样)并覆盖 (>) 到另一个(就像我想要的那样做)?

【问题讨论】:

    标签: linux bash stdout tee


    【解决方案1】:

    使用tee 命令将标准输出“拆分”到多个目标。

    ./myprogram | tee "$g-$number-results.txt" >> $g-results.txt
    

    tee 将其标准输入写入一个(或多个)命名文件以及标准输出,因此上述管道还将myprogram 的每个实例的输出写入一个唯一的每次运行输出文件作为所有 $g 运行的聚合输出到一个文件。

    您还可以聚合内部 for 循环的输出,而不是附加到文件中。

    for g in $groups; do
        # Set the group settings based on the value of $g
        for n in $numbers; do
            # Set the number settings based on the value of $n
            ./myprogram | tee "$g-$number-results.txt"
        done > "$g-results.txt"
    done
    

    【讨论】:

    • 太棒了!不知道for 循环聚合。也不知道 tee 做了多次写入。
    【解决方案2】:

    既然您已经列出了tee 命令:

    ./myprogram | tee $g-$n-results.txt >> $g-results.txt
    

    【讨论】:

      【解决方案3】:

      作为一种简单的方法而不是:

      ./myprogram >> $g-results.txt
      

      您可以捕获一次输出并写入两次:

      $out=$(./myprogram)
      echo "$out" >> "$g-results.txt"
      echo "$out" > "$g-$n-results.txt"
      

      【讨论】:

      • 谢谢,但我需要在运行时扫描和监控文本文件。 (我没有提到这一点,但这是我的要求。)
      • 哦,好吧,在这种情况下,tee 的答案可能对你更有效。
      【解决方案4】:

      使用 tee 两次。

      myprog | tee -a appendFile.txt | tee overwriteFile.txt

      就像这样,它也会打印到标准输出。如果需要,您可以在末尾添加一些内容以将其传递给其他内容。

      如果您需要在 sed 之间进行任何操作,那么您就是您的朋友。

      【讨论】:

      • 没错,但我相信如果您希望一个 tee 附加 (-a) 而另一个 tee 覆盖,您需要这样做。
      猜你喜欢
      • 1970-01-01
      • 2018-05-14
      • 1970-01-01
      • 2010-11-18
      • 2014-02-05
      • 2021-12-29
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多