Bash 脚本:将流从串行端口 (/dev/ttyUSB0) 保存到文件,直到出现特定输入(例如 eof)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/13395222/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash script: save stream from Serial Port (/dev/ttyUSB0) to file until a specific input (e.g. eof) appears
提问by user1822048
I need a bash script to read the data stream from a Serial Port (RS232 to USB adapter - Port: /dev/ttyUSB0). The data should be stored line by line in a file until a specific input (for example "eof") appears. I can give any external input to the Serial Port. Till now I use cat to read the data, which works fine.
我需要一个 bash 脚本来从串行端口(RS232 到 USB 适配器 - 端口:/dev/ttyUSB0)读取数据流。数据应逐行存储在文件中,直到出现特定输入(例如“eof”)。我可以为串行端口提供任何外部输入。到目前为止,我使用 cat 读取数据,效果很好。
cat /dev/ttyUSB0 -> file.txt
The problem is, that I need to finish the command myself by entering cntr+C, but I don't know exactly when the data stream ends and the ttyUSB0 file does not gerenate an EOF. I tried to implement this myself, but did not find a convenient solution. The following command works, but I don't know how to use it for my problem ("world" will create a "command not found" error):
问题是,我需要通过输入 cntr+C 自己完成命令,但我不知道数据流何时结束并且 ttyUSB0 文件不会生成 EOF。我试图自己实现这一点,但没有找到方便的解决方案。以下命令有效,但我不知道如何将其用于我的问题(“world”将创建“command not found”错误):
#!/bin/bash
cat > file.txt << EOF
hello
EOF
world
The following code works for my problem, but it takes too much time (the data stream consists of ~2 million lines):
以下代码适用于我的问题,但需要太多时间(数据流包含约 200 万行):
#!/bin/bash
while read line; do
     if [ "$line" != "EOF" ]; then
          echo "$line" >> file.txt
     else
          break
     fi
done < /dev/ttyUSB0
Has anyone a convenient possibility for my problem?
有没有人为我的问题提供方便的可能性?
采纳答案by Aaron Digulla
Try awk(1):
尝试awk(1):
awk `
/EOF/ {exit;} 
 {print;}` < /dev/ttyUSB0 > file.txt
This stops when it sees the line EOFand prints everything else to file.txt
当它看到该行EOF并将其他所有内容打印到file.txt

