2

I have to create a script that takes the argument that should be the name of a directory. From there it has to print all the files and then print out the largest one and its size. Please help! Would an array with ls -l help?

yourfilenames=`ls $1`
for eachfile in $yourfilenames
do
   echo $eachfile
done
linda
  • 21

1 Answers1

0

You can use the du command to get the size of specific file(s).

If you want to get the output of all files and then print the largest one you can use this:

find /path/to/yourDirectory/ -type f -exec du  {} + | sort -rn | tee  >(echo -e "\nThe largest one is: $(head -1)")

The command find /path/to/yourDirectory/ -type f -exec du {} + will get the size only of the files (subdirectories will not be considered for printing their size, only their files)

With sort -nr the output will be sorted from largest files to smallest ones.

With tee >(echo -e "\nThe largest one is: $(head -1)") the output will be redirected to the stdout and will also be redirected to the process echo -e ... and therefore $(head -1) will print only the first line of the redirected output which represent the largest file size.

When you print with this: echo -e "\nThe largest one is: $(head -1)" the output will be something like this:

The largest one is: 736K        ./path/to/yourdir/largestfilesize

As you can see above the size is printed before the path. If you want to get the path before the size you could use:

find /path/to/yourDirectory/ -type f -exec du  {} + | sort -rn | \
tee  >(echo -e "\nThe largest one is: $(head -1 | awk -v OFS='   ' '{print $2,$1}')")

If you want to get the file sizes in human-readable format (4M,5G,3K, etc) then you should use the correct options to print in that format:

find /path/to/yourDirectory/ -type f -exec du -h {} + | sort -rh | \
tee  >(echo -e "\nThe largest one is: $(head -1)")

#or

find /path/to/yourDirectory/ -type f -exec du -h {} + | sort -rh
tee >(echo -e "\nThe largest one is: $(head -1 | awk -v OFS=' ' '{print $2,$1}')")

#du -h prints the file sizes in human readable format #sort -h will sort the output comparing the human #readable numbers (e.g., 4M,5G,3K, etc)