awk 脚本中的 Gunzip

1 awk text-processing

我正在脚本中创建一个输出文件,awk然后我想压缩该文件。

输入文件 - Marks.txt

Student1:AP:Maths:30:Science:43
Student2:AP:Maths:23:Science:35
Student3:Non_AP:Maths:17:Science:33
Run Code Online (Sandbox Code Playgroud)

我的代码如下所示

BEGIN{
   FS = ":"
}

$2 == "AP"{
 print $3, $4 > "maths_AP.txt"
}

$2 == "Non_AP"{
 print $3, $4 > "maths_non_AP.txt"
}

{...} #some other processing not relevant to question
Run Code Online (Sandbox Code Playgroud)

我想将 和 都创建maths_AP.txtmaths_non_AP.txt压缩文件。一些论坛建议使用gunzip函数,但我不明白如何将它放在脚本中。

Ed *_*ton 8

awk 是一个用于操作文本的工具。shell 是一种用于操作(创建/销毁)文件和进程以及对其他工具的调用进行排序的工具。因此,您通常不应该从 awk 内部顺序调用其他工具,因为这是 shell 的工作,而是使用 awk 操作文本,然后让 shell 调用任何其他工具,例如未经测试的工具:

mkdir out &&
sort -t':' -k3,3 -k2,2 Marks.txt |
awk '
    BEGIN { FS=OFS=":" }
    { key = "out/" $3 "_" $2 ".txt" }
    key != out {
        close(out)
        out = key
    }
    { print > out }
' &&
for file in out/*.txt; do
    zip "$file" &&
    rm -f "$file"         # assuming you want to discard the .txt file
done
Run Code Online (Sandbox Code Playgroud)

上述内容适用于任何版本的工具。close()一旦超过同时打开文件的最大数量阈值(我发现小于 20 个),任何不调用的 awk 解决方案都会在大多数 awk 版本中失败。