如何为ls -l命令列着色

时间:2014-01-29 09:34:42

标签: linux bash shell

我想知道是否有可能ls -l有色。当然,我不是在谈论--color。 我在ls -l命令中找到了显示八进制权限的有用别名,现在,它可以为它着色吗?以同样的方式,我可以ls -l,以红色或其他方式显示仅权限吗?

4 个答案:

答案 0 :(得分:2)

您可以使用多个实用程序来执行此操作,例如将ls (OPTIONS...)的输出汇总到supercat(在确定规则之后)。或highlight(定义规则后)。

或者使用awk / sed进行基于正则表达式的漂亮打印。例如。在awk中使用gensub,您可以将ANSI颜色代码插入输出...

答案 1 :(得分:1)

我想到的第一件事就是你可以使用--color=auto

ls -l --color=auto

创建别名非常方便:

alias lls='ls -l --color=auto'

但是我看到你不想那样。为此,我们必须创建一个使用echo -e "colours..."

的更复杂的函数
print_line () {
        red='\e[0;31m'
        endColor='\e[0m'

        first=${1%% *}
        rest=${1#* }
        echo -e "${red}$first${endColor} $rest"
}

lls () {
        IFS=$'\n'; while read line;
        do
        #       echo "$line"
                print_line $line
        done <<< "$(find $1 -maxdepth 1 -printf '%M %p\n')"
}

如果您将它们存储在~/.bashrc并将其来源(. ~/.bashrc),那么只要您执行lls /some/path,它就会执行这些功能。

答案 2 :(得分:1)

我不知道如何使用颜色代码,但grep--color选项
如果ls -l的第一行对您不重要,您可以考虑使用grep

ls -l | grep --color=always '[d-][r-][w-][x-][r-][w-][x-][r-][w-][x-]'

或缩写形式:

ls -l | grep --color=always '[d-]\([r-][w-][x-]\)\{3\}'

答案 3 :(得分:0)

如果您询问是否有选项可以在中指定自定义列特定颜色,我不这么认为。但你可以做点什么。

> red() { red='\e[0;31m'; echo -ne "${red}$1  "; tput sgr0; echo "${*:2}"; }
> while read -r line; do red $line; done < <(ls -l)