将AWK输出到CSV的Bash脚本 [英] Bash Script with AWK output to CSV

查看:110
本文介绍了将AWK输出到CSV的Bash脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在AWK脚本的此处上提供了惊人的帮助,并以为自己觉得这真的很酷我在CLI上监视的输出与CSV文件完全相同.我做了研究,发现了一个很好的答案

I had amazing help on an AWK script here and thought to myself it would be really cool to have the exact same output I am monitoring on the CLI to go to a CSV file. I did research and found a great answer here, it basically showed code like this:

awk '{print $1","$2","$3","$4","$5}' < /tmp/file.txt > /tmp/file.csv

我遇到的第一个问题是/tmp/file.txt,因为我的代码已经在生成带有分隔值的字符串.我不知道我的变量是否可以在不运行所有新AWK命令的情况下工作,所以我希望尽可能地将其标记到上一个AWK命令的末尾.但是我不知道如何在我正在使用的实际脚本中实现相同的概念.有人可以告诉我格式化格式,我需要将其标记到脚本的末尾吗?

The first issue I have is /tmp/file.txt is not needed as my code is already producing the string with separated values. I don't know if my variables would work without running all new AWK commands, so I would prefer to just tag it to the end of the previous AWK command if possible. But I don't know how to implement the same concept within the actual script I am using. Could anyone show me the formatting schema I would need to tag this into the end of my script?

我不断发展的脚本如下:

My ever-evolving script looks like this:

#!/bin/bash
CURRENT_DATE=`date +%Y-%m-%d`
tail -fn0 /var/log/pi-star/MMDVM-"$CURRENT_DATE".log | gawk '
match($0, /received.*voice header from ([[:alnum:]]+) to ([[:alnum:]]+ 
[0-9]+)/, a) {
in_record = 1
call_sign = a[1]
channel = a[2]
}
in_record && match($0, /DMR ID: ([0-9]+)/, a) {
dmr_id = a[1]
}
in_record && match($0, /([0-9.]+) seconds, ([0-9]+)% packet loss, BER: 
([0-9.]+)%/, a) {
in_record = 0
print call_sign, channel, dmr_id, a[1], a[2], a[3]
}
' OFS=,
done

我仍然想通过终端进行监视,我只是认为将附加到CSV的输出作为锦上添花.我在想什么吗?应该只是一个单独的脚本吗?如果可以,怎么办?

I still want to monitor via the terminal, I just think the appended output to CSV would be the icing on the cake. Am I overthinking it? Should it just be a separate script? If so, how?

推荐答案

在另一个线程上发布了具有更好描述的问题后,有人给出了正确答案.他说,基本上我所看到的是在进入管道时使用awk缓冲输出(因为开销较低),但是在进入TTY时立即将其写入.他接着通过从awk程序调用fflush()来提供解决方案.

After posting the question with a better description on another thread someone responded with a correct answer. He said that basically what I was seeing is awk buffering output when it's going to a pipeline (since that's lower-overhead), but writing it immediately when it's going to a TTY. He went on to offer a solution by calling fflush() from the awk program.

在打印命令后调用fflush(),添加一个额外的命令fflush()."

"Call fflush(), after your print command, add an extra command fflush()."

解决了.谢谢大家的努力.

That fixed it. Thank you all for your efforts.

这篇关于将AWK输出到CSV的Bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆