Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find name of smallest file in Linux?

Tags:

linux

filesize

Suppose that you have to find the name of the 4th smallest (non-hidden) file in the directory

What is the right command to do this? Suppose I'm a guy who only knows ls -l, head, tail, line, and awk '{print}' statement.

like image 989
luc Avatar asked Feb 02 '26 05:02

luc


2 Answers

From man ls: -S sorts the output by size descending, -r reverses the order of the output

So my solution would look like

ls -rS | sed -n '4p'

or, alternatively

ls -rS | awk 'NR==4'
like image 50
Dmytro Sirenko Avatar answered Feb 04 '26 00:02

Dmytro Sirenko


Parsing ls is not safe because it is difficult and error prone to handle strange characters like spaces and newlines in filenames.

I would recommend using the following approach which is more robust since it uses null-terminated line endings.

count=0
while IFS= read -r -d '' line; do
    ((++count == 4)) && echo "${line#* }" && break
done < <(find . -type f -maxdepth 1 -printf '%s %p\0' | sort -zn)
like image 34
dogbane Avatar answered Feb 04 '26 00:02

dogbane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!