我有一个正在使用的聊天脚本
tail -f chatlog.txt
显示聊天。编写消息,以便在回显时,它以彩色文本形式输出。
chatlog.txt:
20:39 \033[4;33musername\033[0m: sowith all of my experiance
20:39 \033[4;33musername\033[0m: we shall proveil
20:40 \033[4;33musername\033[0m: the taxi jobs are very
20:40 \033[4;33musername\033[0m: yes
21:02 \033[4;34mJacob\033[0m has joined the chat!
如果我使用此代码显示它工作正常:
var=$(tail chatlog.txt)
echo -e "$var"
但如果我用tail -f chatlog.txt
显示它没有颜色。我尝试了其他解决方案,但似乎都没有。
您的输出包含文字转义序列;因此,您需要的只是一个程序,它将识别这些并用它们引用的字符替换它们。在符合POSIX的shell中,printf %b
将执行此操作。
从而:
tail -f chatlog.txt | while IFS= read -r line; do printf '%b\n' "$line"; done
有关BashFAQ #1机制的一般性讨论,请参阅while read
。提出一些重点:
IFS=
可防止从行修剪前导和尾随空格。-r
的read
参数可以防止read
删除文字反斜杠。