stm*_*unk 5 pipe sed text-processing tr stdin
我正在调试一个嵌入式服务器,该服务器将连续的单行文本输出到指定的网络端口。流中的任何位置都没有换行符,但它是文本数据,我想在输出时对其进行格式化。我尝试使用 tr (翻译)将流中的字符交换为有效的换行符,但是不可能找到始终可以被换行符明智地替换的唯一单个字符。我最初的想法是使用 sed 将换行符添加到 2-3 个字符的模式中,但因为 sed 是基于行的,并且流是永无止境的单行,所以 sed 将永远不会完成该过程!是否有基于非行的 sed 替代方案?
这就是fold
目的:
NAME
fold - wrap each input line to fit in specified width
SYNOPSIS
fold [OPTION]... [FILE]...
DESCRIPTION
Wrap input lines in each FILE, writing to standard output.
With no FILE, or when FILE is -, read standard input.
Mandatory arguments to long options are mandatory for short options
too.
-b, --bytes
count bytes rather than columns
-s, --spaces
break at spaces
-w, --width=WIDTH
use WIDTH columns instead of 80
--help display this help and exit
--version
output version information and exit
Run Code Online (Sandbox Code Playgroud)
正如您在上面看到的,它可以根据宽度折叠行,这样您就可以得到 100 个字符的行:
command_that_reads_from_port | fold -w 100
Run Code Online (Sandbox Code Playgroud)
这是一个标准程序,是 GNU coreutils 的一部分,因此它应该存在于任何 GNU 系统上。
解决方案如下
stdbuf -o0 ncat -ul 51002 | stdbuf -o0 fold | sed "s/\[15/\&\[15/g" -u | stdbuf -o0 tr -d '\n' | tr "&" "\n"
Run Code Online (Sandbox Code Playgroud)
其中 [15 是我想要在其前面添加换行符的模式。有点解决办法,但效果很好。