简体   繁体   中英

How to “filter” a tail output throug awk and grep?

On a special console I like to filter some informations from /var/log/syslog. That was not really tricky:

tail -f /var/log/syslog | awk '{print $2,$1,$9,$3,"\033[1;36m"$17 "\033[0m","\033[1;33m"$23 "\033[0m","\033[1;36m"$19 "\033[0m","\033[1;33m"$24 "\033[0m","\033[1;38m"$26"\033[0m","\033[1;32m"$13"\033[0m","\033[1;31m"$20 "\033[0m";}'

But now I want to pipe this through grep for a special field. Just adding a "| grep Fieldname" does not work, even not grep first, awk later (which would make more sense).

Could you please give me a tip?

Don't use grep , do the pattern match in awk .

tail -f /var/log/syslog | awk '/Fieldname/ {print $2,$1,$9,$3,"\033[1;36m"$17 "\033[0m","\033[1;33m"$23 "\033[0m","\033[1;36m"$19 "\033[0m","\033[1;33m"$24 "\033[0m","\033[1;38m"$26"\033[0m","\033[1;32m"$13"\033[0m","\033[1;31m"$20 "\033[0m";}'

If you really need to use grep , you can use the --line-buffered option so it doesn't buffer the output.

tail -f /var/log/syslog | grep --line-buffered Fieldname | awk '{print $2,$1,$9,$3,"\033[1;36m"$17 "\033[0m","\033[1;33m"$23 "\033[0m","\033[1;36m"$19 "\033[0m","\033[1;33m"$24 "\033[0m","\033[1;38m"$26"\033[0m","\033[1;32m"$13"\033[0m","\033[1;31m"$20 "\033[0m";}'

If you want to grep the output of awk , you should use fflush() after printing each line to flush the buffer immediately.

tail -f /var/log/syslog | awk '{print $2,$1,$9,$3,"\033[1;36m"$17 "\033[0m","\033[1;33m"$23 "\033[0m","\033[1;36m"$19 "\033[0m","\033[1;33m"$24 "\033[0m","\033[1;38m"$26"\033[0m","\033[1;32m"$13"\033[0m","\033[1;31m"$20 "\033[0m"; fflush();}' | grep Fieldname

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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