I am a Novice programmer. I am not asking for you to build the program for me. I just hope to get some pointers or sample code to help solve my problem.
I have a simple question that is eluding me. Let’s first start with what I am trying to do. I need to do the following.
I need to find the top 10 largest files on a filesystem. (done)
I sort them from largest to smallest (done)
I store the list in an array ( need help on this)
Next, I calculate the percentage of space each file uses on the filesystem. (done)
I then print them on the screen so I can see the files.
Here is the problem that I am having. When I search for files, if I find one that has spaces in the name it causes two problems. First, it messes up how the size and file name are stored. Names with spaces take up 2 or more spots. It messes up the array so my calculations are wrong or fail.
I use the following to find the largest files.
array=( $(find ${fsystem} -xdev -type f -exec du -ax {} + | sort -nr | head ) )
I index the array. Even elements are file size. Odd are file names. I do not work on the filenames other than print them out. When a name has spaces this fails, and things get mixed up. I want a way to have the full path/filename in the odd array indexes. and the File size in the even index.
extra points if you can show me how to calculate using the human-readable format. ie number with a G, M, K, or B suffix.
Here is the script I created
#get filesystem name
read -p "Enter problem filesystem name: " fsystem
#Get the size of filesystem in default format used for calculations.
v1="$(df | grep -i ${fsystem} | awk '{print $2}')"
#get the size in human readable format for printing.
v2="$(df -h | grep -i ${fsystem} | awk '{print $2}')"
#find the top 10 largest files in default format for calculations.
array=( $(find ${fsystem} -xdev -maxdepth 10 -type f -exec du -ax {} + | sort -nr | head ) )
#find the top 10 larges files in human readable format for printing.
array2=( $(find ${fsystem} -xdev -maxdepth 10 -type f -exec du -shx {} + | sort -hr | head ) )
echo "${fsystem} has ${v2} of space"
len=${#array[@]}
i=0
echo "File Size %used filename"
while [ $i -le ${array[$i]} ]
do
# calculate size of the files
fsize=${array[$i]}
fsize2=${array2[$i]}
pct="$( echo " 100/${v1}*${array[$i]}" | bc -l )"
pct=( $(echo "${pct}" | cut -c1-6 ))
outp="${fsize2} "
outp="${outp} ${pct}% "
i=$((i+1)) # incriment i
# print output to screen
outp="${outp} ${array[$i]} "
echo $outp
i=$((i+1))
done