2017-07-27 46 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