linux - 是否可以将 awk 中的打印语句通过管道传输到多个文本文件?

标签 linux bash shell awk scripting

我认为这个问题不言而喻。我有两个文本文件:file1 和 file2。这是在 bash 脚本中使用 awk 的示例代码:

编辑:我正在使用 gnu awk

我的脚本:

val=3

awk 'if ("'$val'" == "3")
         print "Hello" >> "'$PWD/file1.txt'"
     else 
         print "Goodbye" #append to file1.txt and file2.txt
     '

我不想要这样的东西: 值=3

awk 'if ("'$val'" == "3")
         print "Hello" >> "'$PWD/file1.txt'"
     else {
         print "Goodbye" >> "'$PWD/file1.txt'" 
         print "Goodbye" >> "'$PWD/file2.txt'"
     }'

我知道在 bash 中你可以使用 tee 来传输到多个文件。它可以在 gnu awk 中使用吗?如果是这样,那又如何?在 gnu awk 中还有其他方法吗?

最佳答案

GNU Awk 手册显示了 how to simulate tee with awk 的示例.这可能是一个很好的起点。

基本思想是将各种输出文件名存储在一个数组中——然后遍历该数组以依次发送每个文件的输出。在你的情况下,像那样(我直接输入 SO——当然,你必须根据你的需要调整/修复):

BEGIN {
  output[0] = "'$PWD/file1.txt'" 
  output[1] = "'$PWD/file1.txt'" 
  ...
}

{
    for (i in output)
        print "Goodbye!" >> output[i]
}

I know that in bash you can use tee to pipe to multiple files. Can it be used in gnu awk?

如果非 awk 唯一的解决方案是可以接受的,另一个选择是将一些文件描述符重定向到外部 bash 脚本中的 tee,然后将输出发送到那个 fd在需要时来自 awk。这是一个简单的例子:

#!/bin/bash

exec 4<> >(tee file1.txt file2.txt)

awk '{ print NR;                        # send only to stdout
       print "READ:" $0 >> "/dev/fd/4"; # send to `tee`
}'

产生:

sh$ (echo a; echo b) | ./a.sh
1
2
READ:a
READ:b
sh$ cat file1.txt 
READ:a
READ:b
sh$ cat file2.txt 
READ:a
READ:b

关于linux - 是否可以将 awk 中的打印语句通过管道传输到多个文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24938239/

相关文章:

java - 使用 find 将文件传递到 jar

macos - OSX 上的 bash : How to determine if network file (AFP) is in use?

shell - Hbase put shell 命令

shell - 通过 shell 脚本检查 Tomcat 是否正在运行

linux - Xlib中心窗口

linux - 为什么 C99 提示存储大小?

json - 使用 jq 或 Python 解析 JSON

linux - Makefile 通配符问题

bash - 在非交互式Shell session 中运行多个命令并解析输出

shell - 如何在终端中将正则表达式模式打印为字符串?