简体   繁体   English

着色尾巴输出重击

[英]coloring tail output bash

I have a chat script wich is using 我正在使用一个聊天脚本

tail -f chatlog.txt

to display the chat. 显示聊天。 The messages are writen so that when you echo it, it outputs as colored text. 编写消息是为了使您在回显时将其输出为彩色文本。

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!

if i display using this code it works fine: 如果我使用此代码显示,效果很好:

var=$(tail chatlog.txt)
echo -e "$var"

代码输出 But if i display it with tail -f chatlog.txt there is no color. 但是,如果我用tail -f chatlog.txt显示它,则没有颜色。 I have tried other solutions but none seemed to work. 我尝试了其他解决方案,但似乎都没有用。

Your output contains literal escape sequences; 您的输出包含文字转义序列; thus, all you need is a program which will recognize those and replace them with the characters they refer to. 因此,您所需要的就是一个程序,该程序将识别这些字符并将其替换为它们所指的字符。 In POSIX-compliant shells, printf %b will perform this operation. 在POSIX兼容的外壳程序中, printf %b将执行此操作。

Thus: 从而:

tail -f chatlog.txt | while IFS= read -r line; do printf '%b\n' "$line"; done

See BashFAQ #1 for a general discussion of the while read mechanism. 有关while read机制的一般讨论,请参见BashFAQ#1 To call out some of the important points: 指出一些重要点:

  • Using IFS= prevents leading and trailing whitespace from being trimmed from lines. 使用IFS=可以防止从行中修剪前导和尾随空格。
  • Using the -r argument to read prevents literal backslashes from being removed by read . 使用-r参数read可以防止read删除原义的反斜杠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM