Ced*_*ric 15 shell-script tail text-processing
执行 a 时tail -f error.log,如何在 3 秒内未向文件附加任何内容后以编程方式插入换行符?
(显然,一旦添加了一个换行符,在将另一行文本添加到日志文件之前,不应添加其他换行符)
例如,这些行被附加到 error.log :
foo
bar
boo [[wait 4 seconds]]
2far
2foo
2bar
2boo [[wait 40 seconds]]
2far
Run Code Online (Sandbox Code Playgroud)
这将是控制台中的输出:
foo
bar
boo
2far
2foo
2bar
2boo
2far
Run Code Online (Sandbox Code Playgroud)
Sté*_*las 14
您始终可以手动实现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
Run Code Online (Sandbox Code Playgroud)
或者,如果 3 秒内没有输入,tail -f则进行拖尾并用于perl插入换行符:
tail -f file | perl -pe 'BEGIN{$SIG{ALRM} = sub {print "\n"}} alarm 3'
Run Code Online (Sandbox Code Playgroud)
那些假设输出本身没有减慢(例如当输出进入未主动读取的管道时)。
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)
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
用法:
tail -f error.log | python tailing_by_time.py 3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1922 次 |
| 最近记录: |