每 X 秒打印一行(如每 X 行打印一行)

  • 本文关键字:打印 一行 如每 bash sed
  • 更新时间 :
  • 英文 :


我知道sed你可以通过管道传输命令的输出,以便你可以print every X lines.
make all | sed -n '2~5'

是否有等效的命令来print a line every X seconds
make all | print_line_every_sec '5'

在 5 秒超时内读取一行并丢弃其他任何内容:

while
# timeout 5 seconds
! timeout 5 sh -c '
# read one line
if IFS= read -r line; then
# output the line
printf "%sn" "$line"
# discard the input for the rest of 5 seconds
cat >/dev/null
fi
# will get here only, if there is nothing to read
'
# that means that `timeout` will always return 124 if stdin is still open
# and it will return 0 exit status only if there is nothing to read
# so we loop on nonzero exit status of timeout.
do :; done

和单行:

while ! timeout 0.5 sh -c 'IFS= read -r line && printf "%sn" "$line" && cat >/dev/null'; do :; done

但也许更简单 - 只需每行丢弃 5 秒的数据:

while IFS= read -r line; do
printf "%sn" "$line"
timeout 5 cat >/dev/null
done

while IFS= read -r line && 
printf "%sn" "$line" &&
! timeout 5 cat >/dev/null
do :; done

如果您希望每 5 秒显示一次最新消息,请尝试:

make all | {
display(){
if  (( $SECONDS >= 5)); then
if  test -n "${last_line+x}"; then
# print only if there is a message in the last 5 seconds
echo $last_line; unset last_line
fi
SECONDS=0
fi
}
SECONDS=0
while true; do
while IFS= read -t 0.001 line; do
last_line=$line
display
done
display
done
}

即使提出的解决方案有趣且美观,恕我直言,最优雅的解决方案也是一个awk解决方案。如果您想发行

make all | print_line_every_sec 5

然后,您必须创建脚本print_line_every_sec如下所示,包括避免无限循环的测试:

#!/bin/bash
if [ $1 -le 0 ] ; then echo $(basename $0): invalid argument '$1'; exit 1; fi
awk -v delay=$1 'BEGIN {t = systime ()}
{if (systime() >= t) {print $0 ; t += delay}}'

这可能对你有用(GNU sed(:

sed 'e sleep 1' file

每n(在上面的例子中为1(秒打印一行。

要每 2 秒打印 5 行,请使用:

sed '1~5e sleep 2' file

您可以通过watch命令进行操作。 如果你只需要每X秒打印一次输出,你可以使用这样的东西:

watch -n X "Your CMD"

如果您需要指定输出的任何更改,使用-d开关会很有用:

watch -n X -d "Your CMD"

最新更新