执行 a 时tail -f error.log
,如何在 3 秒内没有向文件添加任何内容后以编程方式插入换行符?
(显然,一旦添加了一个换行符,就不应添加其他换行符,直到将其他文本行添加到日志文件中为止)
例如,这些行被附加到 error.log :
foo
bar
boo [[wait 4 seconds]]
2far
2foo
2bar
2boo [[wait 40 seconds]]
2far
这将是控制台中的输出:
foo
bar
boo
2far
2foo
2bar
2boo
2far
答案1
您始终可以手动实现tail -f
(在这里,除非您取消注释seek()
,更像tail -n +1 -f
是我们要转储整个文件)perl
:
perl -e '
$| = 1;
# seek STDIN, 0, 2; # uncomment if you want to skip the text that is
# already there. Or if using the ksh93 shell, add
# a <((EOF)) after < your-file
while (1) {
if ($_ = <STDIN>) {
print; $t = 0
} else {
print "\n" if $t == 3;
# and a line of "-"s after 10 seconds:
print "-" x 72 . "\n" if $t == 10;
sleep 1;
$t++;
}
}' < your-file
或者,如果 3 秒内没有输入,则让其tail -f
执行尾部操作并用于插入换行符:perl
tail -f file | perl -pe 'BEGIN{$SIG{ALRM} = sub {print "\n"}} alarm 3'
这些假设输出本身不会减慢(就像当输出进入未主动读取的管道时)。
答案2
bash
+date
解决方案:
while IFS= read -r line; do
prev=$t # get previous timestamp value
t=$(date +%s) # get current timestamp value
[[ ! -z "$prev" ]] && [[ "$((t-prev))" -ge 3 ]] && echo ""
echo "$line" # print current line
done < <(tail -f error.log)
答案3
Python
解决方案(动态时间空隙争论):
tailing_by_time.py
脚本:
import time, sys
t_gap = int(sys.argv[1]) # time gap argument
ts = 0
while True:
line = sys.stdin.readline().strip() # get/read current line from stdin
curr_ts = time.time() # get current timestamp
if ts and curr_ts - ts >= t_gap:
print("") # print empty line/newline
ts = curr_ts
if line:
print(line) # print current line if it's not empty
用法:
tail -f error.log | python tailing_by_time.py 3