语法高亮/着色猫 [英] Syntax highlighting/colorizing cat
问题描述
是否有一种方法可以像 grep
那样为 cat
的输出着色.
Is there a method to colorize the output of cat
, the way grep
does.
对于grep
,在大多数控制台中,它会显示突出显示搜索关键字的彩色输出.否则,您可以通过调用 grep --color
来强制它有没有一种通用的方法可以根据您的个人选择为任何程序的输出着色.
For grep
, in most consoles it displays a colored output highlighting the searched keywords. Otherwise, you can force it by calling grep --color
Is there a generic way to color the output of any program according to your personal choice.
据我所知,程序本身不对颜色负责.它是外壳.
From what I understand, the program itself is not responsible for the colors. It is the shell.
我使用的是 FreeBSD 5.2.1 中的默认 shell,它看起来自 epoch 以来从未见过颜色.
I am using the default shell in FreeBSD 5.2.1 which looks like it has never seen colors since epoch.
推荐答案
cat
语法高亮只是超出了范围.cat
不是为了这个.如果您只想以某种方式为某个文件的整个内容着色(整个文件的颜色相同),您可以使用终端转义序列来控制颜色.
cat
with syntax highlighting is simply out of scope. cat
is not meant for that.
If you just want to have the entire content of some file coloured in some way (with the same colour for the whole file), you can make use of terminal escape sequences to control the color.
这是一个示例脚本,它将根据文件类型选择颜色(您可以使用类似的方法而不是直接调用 cat
):
Here's a sample script that will choose the colour based on the file type (you can use something like this instead of invoking cat
directly):
#!/bin/bash
fileType="$(file "$1" | grep -o 'text')"
if [ "$fileType" == 'text' ]; then
echo -en "\033[1m"
else
echo -en "\033[31m"
fi
cat $1
echo -en "\033[0m"
以上(在支持这些转义序列的终端上)会将任何文本文件打印为粗体",并将任何二进制文件打印为红色.您可以使用 strings
而不是 cat
来打印二进制文件,并且您可以增强逻辑以使其适合您的需要.
The above (on a terminal that supports those escape sequences) will print any text file as 'bold', and will print any binary file as red. You can use strings
instead of cat
for printing binary files and you can enhance the logic to make it suit your needs.
这篇关于语法高亮/着色猫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!