bash:着色输出的第二列


8

假设,我从ls获得以下输出:

$ ls -lAhF /bin
-rwxr-xr-x 1 root root 905K Apr 10  2010 bash*
-rwxr-xr-x 3 root root  31K Dec 26  2011 bunzip2*
-rwxr-xr-x 1 root root 505K Nov 15  2010 busybox*
-rwxr-xr-x 3 root root  31K Dec 26  2011 bzcat*
lrwxrwxrwx 1 root root    6 Jun 24  2012 bzcmp -> bzdiff*
...

我正在寻找一种方法,如何使第二列着色。我知道如何使用sed来为任何图案着色,但是我不知道如何为特定列着色。基本上,我需要'\033[0;31m'在第一个空格之后和'\033[0m'第二个空格的前面插入。还是有更优雅的方法?


1
丑陋:ls --color -l | sed -e $'s/ *[^ ]* /\033[0;31m&\033[0m/'
frostschutz

Answers:


10

借助GNU grep,它已通过PCRE支持构建:

ls -l | GREP_COLORS='mt=1;41;37' grep --color -P '^\S+\s+\K\S+'

sed

on=$(tput setaf 7; tput setab 1; tput bold) off=$(tput sgr0)
ls -l | sed "s/[^[:blank:]]\{1,\}/$on&$off/2"

请注意,using setaf假设终端支持ANSI颜色转义序列,因此您不妨对其进行硬编码,这也将使其不那么冗长。这里使用ksh93(Also bashand zsh)语法:

on=$'\e[1;47;37m' off=$'\e[m'

推广到第n 列:

n=5

GREP_COLORS='mt=1;41;37' grep --color -P "^(\S+\s+){$(($n-1))}\K\S+"

sed "s/[^[:blank:]]\{1,\}/$on&$off/$n"

参考文献


grep -P太棒了。非常感谢。
user1968963 2013年

6

像这样吗

awk -v on="$(tput bold)" -v off="$(tput rmso)" '{ $2=on $2 off }; 1'

编辑:使用适当的tput子命令。


设置$1将中断列对齐。
斯特凡Chazelas

2
严格来说,rmso是取消smso(退出模式),而不是bold。在许多终端(tput rmso取消tput bold)。
斯特凡Chazelas
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.