0

This is the answer I found to display ls with folder/file size

https://stackoverflow.com/a/28582709/1860805

(du -sh ./*; ls -lh --color=no) | awk '{ if($1 == "total") {X = 1}
else if (!X) {SIZES[$2] = $1} else { sub($5 "[ ]*", sprintf("%-7s ",
SIZES["./" $9]), $0); print $0} }'

But it lost the coolness of ls color. If you put --color=always then the size is lost. How to have the colors on the above output? The color has to be same as normal ls -alh output

Ramanan T
  • 179
  • 1
  • 10
  • Please repost your script, using code formatting, not quotation. – Barmar Dec 09 '21 at 03:48
  • The escape sequences used for coloring the output are likely to confuse `awk` when trying to extract the fields. – Barmar Dec 09 '21 at 03:50
  • This is why `ls` defaults to `--color=no` when the output is to a pipe. Most tools that you pipe to can't deal with colored input. – Barmar Dec 09 '21 at 03:51

1 Answers1

1

Finally I wrote a script to print the output and alias to that script. That works like a magic.

alias le=~/bin/ls-ext.sh

Make sure ~/bin is in your PATH This is the ls-ext.sh script

#!/bin/bash

PURPLE=$(tput setaf 5) GREEN=$(tput setaf 2) YELLOW=$(tput setaf 3) NC=$(tput sgr0)
let ln=0

pwd=$1;
if [ "${pwd::1}" = "." ] && [ ${#pwd} -eq 1 ]
then
        pwd=""
elif [ "${pwd: -1}" != "/" ] && [ ${#pwd} -gt 1 ]
then
        pwd="$pwd/"
fi

while read line
do
        ln=$((ln+1));   [ $ln -eq 1 ] &&        continue
        read -r -a array <<< "$line"
        duout=$(du -sh "$pwd${array[8]}" 2>/dev/null|cut -f1)
        [ $? -eq 0 ] && array[4]="$duout"
        if [ "${array[4]: -1}" = "G" ]
        then
                 array[4]="$PURPLE${array[4]}$NC"
        elif [ "${array[4]: -1}" = "M" ]
        then
                 array[4]="$YELLOW${array[4]}$NC"
        else
                 array[4]="$GREEN${array[4]}$NC"
        fi

        lsout="$(ls --color=always -d $pwd${array[8]})"
        if [ "${array[0]:0:1}" = "l" ]
        then
                read -r -a lsarray <<< "$(ls --color=always -lsd $pwd${array[8]})"
                lsout=$(echo "${lsarray[@]:9:${#lsarray[@]}}"|sed 's/[[:space:]]->[[:space:]]/->/')
        fi
        #echo -e "${array[@]::8} $lsout"
        printf "%-11s%3s %-10s%-10s%15s%4s%3s %-4s %s\n" ${array[0]} ${array[1]} ${array[2]} ${array[3]} ${array[4]} ${array[5]} ${array[6]} ${array[7]} $lsout
done  < <(ls -al --color=no $pwd )
echo "Total: $((ln-1))"

The output looks like this ls-ext.sh output with size and colors

Ramanan T
  • 179
  • 1
  • 10