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

BЈо*_*вић 4 linux bash perl

我尝试从这个建议创建一个脚本,如下所示:

#!/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
Run Code Online (Sandbox Code Playgroud)

当我没有向脚本传递任何参数时,它显示文件的黑尾,但是当我传递参数时,每一行都是红色的.我希望它只为包含传递给脚本的单词的行着色.

例如,这将包含单词"info"的彩色线条:

./color_lines.sh info
Run Code Online (Sandbox Code Playgroud)

如何更改脚本以使用一个参数?

per*_*eal 9

不要引用参数变量:

tail -f input | perl -pe 's/.*'$1'.*/\e[1;31m$&\e[0m/g'
Run Code Online (Sandbox Code Playgroud)

您也可以使用grep:

tail -f input | grep -e $1 -e ''  --color=always
Run Code Online (Sandbox Code Playgroud)

并使用grep为整行着色:

tail -f input | grep -e ".*$1.*" -e ''  --color=always
Run Code Online (Sandbox Code Playgroud)