2017-07-27 45 views
2

我有一个COM_port,我听这样的:重定向bas​​h的输出到新的文件每隔10秒

nc -l -p 1234. 

所以,我想输出重定向到一个文件中,在每10秒一个新的文件。 我知道如何将流量重定向到一个文件:

nc -l -p 1234 > file.txt 

但如何写流向新的文件每隔10秒? (前10秒file_10.txt,第二个file_20.txt等)。 我害怕丢失流量数据。 怎么可能做到这一点?

谢谢。

+0

如果连接超过10秒持续时间较长(或跨越一个变化事件),你要输入的一部分记录到一个文件中的一部分到另一个,或者是你接通的初始时间仅根据连接? – ghoti

回答

6
#!/usr/bin/env bash 
#    ^^^^- IMPORTANT! bash, not /bin/sh; must also not run with "sh scriptname". 

file="file_$((SECONDS/10))0.txt"  # calculate our initial filename 
exec 3>"$file"       # and open that first file 

exec 4< <(nc -l -p 1234)     # also open a stream coming from nc on FD #4 

while IFS= read -r line <&4; do   # as long as there's content to read from nc... 
    new_file="file_$((SECONDS/10))0.txt" # calculate the filename for the current time 
    if [[ $new_file != "$file" ]]; then  # if it's different from our active output file 
    exec 3>$new_file      # then open the new file... 
    file=$new_file      # and update the variable. 
    fi 
    printf '%s\n' "$line" >&3    # write our line to whichever file is open on FD3 
done 
+0

完美! *我可以在Python中编写相同的脚本,我更喜欢什么性能? 谢谢。 – John

+0

Python会比bash有更好的性能; Golang将比Python更好的表现(如果这将会处理非常高的音量,那么我会用它)。 –

+0

哇!那么C呢?它比Golang好吗?非常感谢! – John