问题描述:

I am coding a simple shell script that checks the space of the target path and the space utilization per directory on that target path (example, I am checking space of /path1/home, and also checks how all the folders on /path1/home is consuming the total space.) My question is regarding the output it produces, it is not that pleasing to the eye (uneven spacing). See sample output lines below.

SIZE USER_FOLDER DATE_LAST_MODIFIED

83G FOLDER 1 Apr 15 03:45

34G FOLDER 10 Mar 9 05:02

26G FOLDER 11 Mar 29 13:01

8.2G FOLDER 100 Apr 1 09:42

1.8G FOLDER 101 Apr 11 13:50

1.3G FOLDER 110 Feb 16 09:30

I just want the output format to be in line with the header so it will look neat because I will use it as a report. Here is the code I am using for this part.

ls -1 | grep -v "lost+found" |grep -v "email_body.tmp" > $v_path/Users.tmp

for user in `cat $v_path/Users.tmp | grep -v "Users.tmp"`

do

folder_size=`du -sh $user 2>/dev/null` # should be run using a more privileged user so that other folders can be read (2>/dev/null was used to discard error messages i.e. "du: cannot read directory `./marcnad/.gnupg': Permission denied")

folder_date=`ls -ltr | tr -s " " | cut -f6,7,8,9, -d" " | grep -w $user | cut -f1,2,3, -d" "`

folder_size="$folder_size $folder_date"

echo $folder_size >> $v_path/Users_Usage.tmp

done

echo "Summary of $v_path Disk Space Utilization per folder." >> email_body.tmp

echo "" >> email_body.tmp

echo "SIZE USER_FOLDER DATE_LAST_MODIFIED" >> email_body.tmp

for i in T G M K

do

cat $v_path/Users_Usage.tmp | grep [0-9]$i | sort -nr -k 1 >> $v_path/email_body.tmp

done

Thanks!

EDIT: Formatting

网友答案:

When you print the data use printf instead of echo

cat $v_path/Users_Usage.tmp | while read a b c d e f
do
    printf '%-5s%-7%s%-4s%-4s%-3s-6s' $a $b $c $d $e $f
done

See here

相关阅读:
Top