简体   繁体   English

如何在awk命令中使用命令的输出?

[英]How to use output of a command inside an awk command?

I want to print out the last update of a log file and nothing above it (old logs). 我想打印出一个日志文件的最新更新,而不是上面的任何内容(旧日志)。 Every 5 minutes the log is updated/appended to, and there is no option to overwrite instead of append. 每5分钟更新/添加日志一次,没有选项可以覆盖而不是追加。 The amount of lines per update don't vary now , but I don't want to have to change the script if and when new fields are added. 每次更新行的数量现在不改变,但我不希望有改剧本是否以及何时添加了新的领域。 Each appendage starts with "Date: ...." 每个附件以“日期:..”开头。

This is my solution so far. 到目前为止,这是我的解决方案。 I'm finding the line number of the last occurrence of "Date" and then trying to send that to "awk 'NR>line_num_here filename" - 我正在查找最后一次出现的“日期”的行号,然后尝试将其发送到“ awk'NR> line_num_here文件名”-

line=$(grep -n Date stats.log | tail -1 | cut --delimiter=':' --fields=1) | awk "NR>$line" file.log

However, I cannot update $line! 但是,我无法更新$ line! It always holds the very first value from the very first time I ran the script. 从我第一次运行脚本起,它始终拥有第一个值。 Is there a way to correctly update $line? 有没有办法正确更新$ line? Or are there any other ways to do this? 还是有其他方法可以做到这一点? Maybe a way to directly pipe into awk instead of making a variable? 也许是一种直接将其传递给awk而不是进行变量创建的方法?

The problem in your solution is that you need to replace the pipe in front of awk by a ; 解决方案中的问题是,您需要用a替换awk前面的管道; . These are two separate commands which would normally appear on two separate lines: 这些是两个单独的命令,通常会出现在两个单独的行中:

line=$(...)
awk -v "NR>$line" file

However, you can separate them by a ; 但是,您可以将它们分开; if the should appear on the same line: 如果应该出现在同一行:

line=$(...); awk -v "NR>$line" file

But anyway you can significantly simplify the command. 但是无论如何,您都可以大大简化命令。 Simply use twice awk twice, like this: 只需两次使用两次awk ,如下所示:

awk -v ln="$(awk '/Date/{l=NR}END{print l}' a.log)" 'NR>ln' a.log

I'm using 我正在使用

awk '/Date/{l=NR}END{print l}' a.log

to obtain the line number of the last occurrence of Date . 获取最后一次出现的Date的行号。 This value get's passed via -v ln=... to the outer awk command. 该值通过-v ln=...传递给外部awk命令。

Here's a way you could do it, in one invocation of awk and only reading the file once: 这是一种方法,可以通过awk的调用而只读取一次文件:

awk '/Date/ { n = 1 } { a[n++] = $0 } END { for (i = 1; i < n; ++i) print a[i] }' file

This writes each line to an array a , resetting the counter n back to 1 every time the pattern /Date/ matches. 这会将每一行写入数组a ,每当/Date/模式匹配时,将计数器n重置为1 It then loops through the array once the file has been read, printing all the most recently saved values. 一旦读取了文件,它就会遍历数组,打印所有最近保存的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM