如何使用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-4flag specifies the number of lines).awk '{print "\033[31m" $0 "\033[0m"}': Takes each line fromtailand wraps it in ANSI color codes:\033[31m: Activates red text formatting.$0: Represents the entire line of input fromtail.\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
相关产品推荐
相关产品推荐

