linux - Bash 脚本到带有彩色线条的 tail -f

标签 linux perl bash

我试图从 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/

相关文章:

regex - 在一行匹配后替换为第 N 行中存在的字符串

perl - 将 form-urlencoded 解码为哈希

python - 需要 CGI(或与 IIS 7 兼容的其他解决方案)来处理*大量*上传

linux - 如何从另一个文件中读取文件

linux - bash 脚本中的 ` 是什么?

javascript - 为需要的 Node 模块创建工厂

linux - 发送多个 csv 附件,简单的 Bash 错误?

c - 链接器更喜欢弱符号?

linux - 在 Raspberry Pi (CP210X) 上更新产品/供应商 ID

android - 如何在shell(终端)中执行monkeyrunner命令