Tho*_* B. 7 streaming curl pipe
我有一个 HTTP 端点,可以提供无限的事件流。现在我想使用 curl 记录该流,但同时拆分记录的文件 - 最好基于行号以防止损坏。
我试过 split,但似乎 split 在输入流结束之前什么都不做。
这是我的命令:
stdbuf -oL curl -s http://... | split -l1 - record.chunked.
Run Code Online (Sandbox Code Playgroud)
用于测试:以下命令尝试将 ping 命令的结果拆分为每个文件 1 行的文件。但它不起作用。
ping localhost | split -l1 - out.
Run Code Online (Sandbox Code Playgroud)
是否有另一种(精益,简单,最好没有脚本)的方法来做到这一点?
我知道您说过您想避免为此编写脚本,但我做了一个非常简单的解决方案。看一看:
#!/bin/bash
#
# read infinitely from /dev/stdin and print into files for every 100 lines
# Written by Guy Gastineau. 3/20/2019 - Free to use!
#
# create unique names for the logs
set_filename () {
filename="${HOME}/eventlogs/$(date '+%Y-%m-%d_%H:%M:%S').log"
}
# error if eventlogs dir doesn't exist
if [[ ! -d ${HOME}/eventlogs ]]; then
printf '%s\n' "~/eventlogs doesn't exist. Please create this directory" >&2
exit 1
fi
# initialize vars
idx=0; set_filename
# read from stdin
while read -r line; do
printf '%s\n' "$line" >> $filename # print to file
$(( idx++ )) 2> /dev/null # increment idx, and ignore output
if [[ $idx -ge 100 ]]; then # reset vars when idx gets to 100
idx=0; set_filename
fi
done
Run Code Online (Sandbox Code Playgroud)
如果您希望将日志保存在其他位置,请随意更改文件名的基本路径。另外,更改第 25 行测试中的整数将更改创建新文件之前放入每个文件中的行数。
重要的!只要该脚本可以从 stdin 读取数据,它就会运行。
附言。我对此进行了测试ping google.com | myscript,效果非常好。