简体   繁体   English

Bash脚本尾部-f用彩色线条

[英]Bash script to tail -f with colored lines

I tried to create a script from this suggestion like this : 我尝试从这个建议创建一个脚本,如下所示:

#!/bin/bash

if [ $# -eq 0 ]; then
        tail -f /var/log/mylog.log
fi


if [ $# -eq 1 ]; then
        tail -f /var/log/mylog.log | perl -pe 's/.*$1.*/\e[1;31m$&\e[0m/g'
fi

It shows black tail of the file when I pass no arguments to the script, but every line is red when I pass an argument. 当我没有向脚本传递任何参数时,它显示文件的黑尾,但是当我传递参数时,每一行都是红色的。 I would like it to color only lines which contain the word passed to the script. 我希望它只为包含传递给脚本的单词的行着色。

For example, this would color lines containing word "info" : 例如,这将包含单词“info”的彩色线条:

./color_lines.sh info

How to change the script to work with one argument? 如何更改脚本以使用一个参数?

Do not quote the argument variable: 不要引用参数变量:

tail -f input | perl -pe 's/.*'$1'.*/\e[1;31m$&\e[0m/g'

You can also use grep for this: 您也可以使用grep:

tail -f input | grep -e $1 -e ''  --color=always

and to color the whole line with grep: 并使用grep为整行着色:

tail -f input | grep -e ".*$1.*" -e ''  --color=always

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

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