我试图从 this suggestion 创建一个脚本像这样:
#!/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
当我没有向脚本传递参数时,它显示文件的黑尾,但当我传递参数时,每一行都是红色的。我希望它只为包含传递给脚本的单词的行着色。
例如,这将为包含单词“info”的行着色:
./color_lines.sh info
如何更改脚本以使用一个参数?
最佳答案
不要引用参数变量:
tail -f input | perl -pe 's/.*'$1'.*/\e[1;31m$&\e[0m/g'
您也可以为此使用 grep:
tail -f input | grep -e $1 -e '' --color=always
并使用 grep 为整行着色:
tail -f input | grep -e ".*$1.*" -e '' --color=always
关于linux - Bash 脚本到带有彩色线条的 tail -f,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16911244/