You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用tail命令实现带颜色输出?需红色打印指定文件最后4行

How to Print Last 4 Lines of a File in Red Using tail

Hey there! Great question—adding colored output to your tail command is totally doable with ANSI escape codes, which most modern terminals support. Here's exactly how to get the red-colored last 4 lines of FDECMP1_$$.log:

Method 1: Using tail + awk

This is a clean, straightforward approach:

tail -4 FDECMP1_$$.log | awk '{print "\033[31m" $0 "\033[0m"}'

Let's break down what each part does:

  • tail -4 FDECMP1_$$.log: Grabs the final 4 lines of your target file (the -4 flag specifies the number of lines).
  • awk '{print "\033[31m" $0 "\033[0m"}': Takes each line from tail and wraps it in ANSI color codes:
    • \033[31m: Activates red text formatting.
    • $0: Represents the entire line of input from tail.
    • \033[0m: Resets the terminal back to default formatting—this is crucial, otherwise all subsequent terminal output will stay red!

Method 2: Using tail + sed

If you prefer sed over awk, this works too:

tail -4 FDECMP1_$$.log | sed 's/^/\x1b[31m/; s/$/\x1b[0m/'
  • s/^/\x1b[31m/: Adds the red color code at the start of each line (^ denotes the line beginning).
  • s/$/\x1b[0m/: Adds the reset code at the end of each line ($ denotes the line ending).

Quick Note

This relies on your terminal supporting ANSI escape sequences. Almost all modern terminals (Bash, Zsh, iTerm2, Windows Terminal, etc.) do this, but if you're using a very old or specialized terminal, it might not work (you'll see the raw escape codes instead of color).

内容的提问来源于stack exchange,提问作者Ashish P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:19:54