Par*_*avi 3 command-line io-redirection awk
I want to use the AWK redirection feature and what I've done so far is this :
$ vmstat 1 | awk ' { print $2 > "outfile" } '
Run Code Online (Sandbox Code Playgroud)
*Actually the commands before awk are a lot more complicated , but it's a simplified demonstration.
If I run the above command without redirection , I would get the desired result in the stdout. But after redirecting it to outfile , it's still empty :
$ cat outfile
$
Run Code Online (Sandbox Code Playgroud)
What's wrong with that ?
TIA.
The problem is buffering, it can be disabled.
vmstat 1 | stdbuf -o0 awk '{print $2}' >> out
Run Code Online (Sandbox Code Playgroud)
-o output stream0 流将无缓冲或者也可以称之为vmstat在while循环使用sleep 1
while true; do
vmstat | awk '{print $2}' >> output.file
sleep 1
done
Run Code Online (Sandbox Code Playgroud)
awk缓冲其输出。如果您的 awk 实现提供了它(如 gawk、mawk 1、nawk 和 BSD awk 所做的那样),请使用fflush().
Run Code Online (Sandbox Code Playgroud)fflush([file]) Flush any buffers associated with the open output file or pipe file. If file is missing or if it is the null string, then flush all open output files and pipes.
所以,这样写:
vmstat 1 | awk '{print $2 > "outfile"; fflush()}'
Run Code Online (Sandbox Code Playgroud)
GNU的awk的手动I / O部分上fflush是值得一读。在那里您还会发现fflush已接受下一个 POSIX 标准。
另外,请注意您可以给出vmstat应该输出的样本数。因此,如果您只需要5样本(例如),您可以等待 5 秒直到命令终止,然后文件将包含输出:
vmstat 1 5 | awk '{print $2 > "outfile"}'
Run Code Online (Sandbox Code Playgroud)
1使用 mawk 的语法有点不同:mawk -W interactive '{print $2 > "outfile"; fflush("")}'.
| 归档时间: |
|
| 查看次数: |
397 次 |
| 最近记录: |