Bash 脚本:将流从串行端口 (/dev/ttyUSB0) 保存到文件,直到出现特定输入(例如 eof) [英] Bash script: save stream from Serial Port (/dev/ttyUSB0) to file until a specific input (e.g. eof) appears

查看:62
本文介绍了Bash 脚本:将流从串行端口 (/dev/ttyUSB0) 保存到文件,直到出现特定输入(例如 eof)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个 bash 脚本来从串行端口(RS232 到 USB 适配器 - 端口:/dev/ttyUSB0)读取数据流.数据应逐行存储在文件中,直到出现特定输入(例如eof").我可以给串口提供任何外部输入.到目前为止,我使用 cat 读取数据,效果很好.

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.

cat /dev/ttyUSB0 -> file.txt

问题是,我需要自己通过输入 cntr+C 来完成命令,但我不知道数据流何时结束并且 ttyUSB0 文件不会生成 EOF.我试图自己实现这一点,但没有找到方便的解决方案.以下命令有效,但我不知道如何使用它来解决我的问题(world"将创建command not found"错误):

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):

#!/bin/bash
cat > file.txt << EOF
hello
EOF
world

以下代码适用于我的问题,但耗时太长(数据流由约 200 万行组成):

The following code works for my problem, but it takes too much time (the data stream consists of ~2 million lines):

#!/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?

推荐答案

试试awk(1):

awk `
/EOF/ {exit;} 
 {print;}` < /dev/ttyUSB0 > file.txt

当它看到 EOF 行时停止,并将其他所有内容打印到 file.txt

This stops when it sees the line EOF and prints everything else to file.txt

这篇关于Bash 脚本:将流从串行端口 (/dev/ttyUSB0) 保存到文件,直到出现特定输入(例如 eof)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆